Home Blog Page 12

NodeJS Script to upload file to Google Drive using GoogleAPI’s

0
Nodejs upload drive to google drive

Hi Guy’s Welcome to Proto Coders Point. This article is on how to upload files to Google Drive using NodeJS.

Uploading a file to google drive by using nodejs code take several steps, which include steps:

  • Creating Project in Google Cloud Console.
  • Enabling Google Drive API.
  • Creating Service Account Credentials.
  • Creating NodeJS Project and Install Necessary Libraries.
  • NodeJS Code to Upload File to Google Drive.

Step 1: Setup a Google Cloud Console Project:

  • Go to Google Cloud Console : https://console.cloud.google.com/.
  • Create a new Project or select an existing one.
  • Now Navigate to “API’s & Services” > “Library”.
  • In Search for “Google Drive API” and click on enable button for your project.
how to enable google drive api

Step 2: Create Service Account Credentials API

In google cloud console, Navigate to “API’s & Services” > “Credentials”.

Click on “Create Credentials” > Select “Service Account”.

Enter Service Account Name, Service account ID then click DONE.


Step 3: Creating API Key JSON File for authentication

Once Service Account is been created, click on Service Account Email as soon in above image.

Then Click on Keys > Add Key > Create New Key

service account api key json file

This will create a json file download it, It contain api key by making use of which you can write a nodeJS Script that can upload files into your google drive.


Step 4: Creating a Folder & Give Access

Now, Once Service Account email is created, We need to create a Folder on Google Drive that will have full access permission for the service account we created, Basically share that folder with Service Account we created in above step.

Click on 3 dot on the folder that you want to share with service account, then click on share and enter the email address of service account and done.


Step 5: Creating NodeJS Project

Create a folder & open a terminal in that folder path itself.

In Terminal/CMD enter npm init to make normal folder into nodeJS project


Step 6: Installing required Library/Module

To upload files into google drive from Nodejs script we need few library:

fs (File Sytem) -> To work with Files of System.

googleapis -> To communicate with google drive API.

Install those using below cmd:

npm install fs googleapis

Step 7: Finally NodeJS Script/Function to Upload file to Google Drive using Google Drive API

In your NodeJS Project, paste the credential .json file download from above step.

In my project I have created a javascript code by name app.js, what will have a function that will upload file to google drive.

app.js

const fs = require('fs');
const { google }= require('googleapis');

const apikeys = require('./apikeys.json');
const SCOPE = ['https://www.googleapis.com/auth/drive'];

// A Function that can provide access to google drive api
async function authorize(){
    const jwtClient = new google.auth.JWT(
        apikeys.client_email,
        null,
        apikeys.private_key,
        SCOPE
    );

    await jwtClient.authorize();

    return jwtClient;
}

// A Function that will upload the desired file to google drive folder
async function uploadFile(authClient){
    return new Promise((resolve,rejected)=>{
        const drive = google.drive({version:'v3',auth:authClient}); 

        var fileMetaData = {
            name:'mydrivetext.txt',    
            parents:['1bZoTbqCew34MGr1DfgczcA40ECM_QhKg'] // A folder ID to which file will get uploaded
        }

        drive.files.create({
            resource:fileMetaData,
            media:{
                body: fs.createReadStream('mydrivetext.txt'), // files that will get uploaded
                mimeType:'text/plain'
            },
            fields:'id'
        },function(error,file){
            if(error){
                return rejected(error)
            }
            resolve(file);
        })
    });
}

authorize().then(uploadFile).catch("error",console.error()); // function call

Now run the code

node app.js

Flutter Alphabetical Scroll List

0
Flutter Alphabetical Scroll List
Flutter Alphabetical Scroll List

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Article let’s learn how to implement Alphabetical scroll list in flutter.

An Alphabetical Scroll List also known as A-Z Scroll List, is the most commonly used in mobile applications that help users to quickly navigate to any large set of list in an alphabetical order.

Here are some common places where an Aplhabetical Scroll List can be used:

  1. Contact List.
  2. Music & Video Playlist.
  3. Address Books.
  4. Product Lists.
  5. Country or City List.

An Alphabetical Scroll List is versatile UI element that ca be applied in many use case like contact list, music, video, address, country and many more for efficient navigation through the large dataset.

How to Implement alphabetical scroll list in flutter

In Flutter to create an alphabetical listview which can be scrollable using easily A-Z Alphabet, We will be using a dependency/library called azlistview that allow scrolling to a specific items in the list for easy navigation.

Video Tutorial

Install Library into flutter project

Open pubspec.yaml file and under dependencies section add:

dependencies:
  azlistview: ^2.0.0  #version may change in future

After adding the dependencies hit pub get button or enter “flutter pub get” in terminal to download the package into your flutter project as external packages.

Import to use it

import 'package:azlistview/azlistview.dart';

Source Code to Implement A-Z Scroll list in flutter

Flutter Alphabetical Scroll List

In “lib” directory of your flutter project, Create a Dart File by name “CountryList.dart”

CountryList.dart

This will be a class that extends ISuspensionBean which comes with azlistview package.

import 'package:azlistview/azlistview.dart';

class CountryList extends ISuspensionBean{

  final String title;
  final String tag;


  CountryList({required this.title, required this.tag});

  @override
  String getSuspensionTag() {
    // TODO: implement getSuspensionTag
    return tag;
  }

}

main.dart

In this page we will load the list of country name which can we easily alphabetically scrolled to navigate to particular items in the listview using A-Z.

import 'dart:typed_data';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ui/CountryList.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'ProtoCodersPoint.com',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: AlphabeticalListView(items: [
          "Afghanistan", "Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"
        ],),
      ),
    );
  }
}


class AlphabeticalListView extends StatefulWidget {
  final List<String> items;

  AlphabeticalListView({Key? key, required this.items}) : super(key: key);

  @override
  State<AlphabeticalListView> createState() => _AlphabeticalListViewState();
}

class _AlphabeticalListViewState extends State<AlphabeticalListView> {

  List<CountryList> items = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initList(widget.items);
  }

  void initList(List<String> items){
    this.items = items.map((item) => CountryList(title: item,tag: item[0])).toList();
  }


  @override
  Widget build(BuildContext context) {
    return AzListView(data: items, itemCount: items.length, itemBuilder: (context,index){
      final item = items[index];
      return Card(
        child: ListTile(
          title: Text(item.title),
        ),
      );
    });
  }
}

7 Practices to reduce flutter app size

0
flutter app size reduce

To Reducing the size of your Flutter app is a major task and crucial for improving performance, decreasing load times, and enhancing user experience. Below are seven practices to help you achieve a smaller flutter app size:

1. Use SVG Images:

Use SVG Images instead of PNG or JPEG images. As SVG images are vector images, which means they can be scaled to any size without losing image quality. This makes them much smaller than PNG or JPEG images, which are raster images.

2. Compress Images:

Compress your images. Even if you’re using svg images, you can still compress them to further reduced size. There are many online tools that can help you to compress SVG images.

3. Remove unused resources:

Remove unused resources. Before publishing your application, take a look at all of the resources that you’re including in it. Are there any resource that you’re not actually using? if so, remove them. This will help to reduce the size of your app.

4. Use code obfuscator:

use a code obfuscator. A code obfuscator can help to reduce the size of your app by making your code more compact. This is done by remaining vairables, functions, and other elements of your code.

5. use Android App Bundles:

Use Android App Bundles. Android App bundles(AAB’s) are a new way to publish or distribute Android apps in playstore. AAB’s allow you to split your application into multiple APK’s each of which is optimized for a specific devices configuation. This can help to reduce the size of your app from users with older devices.

6. Avoid using large images:

Avoid using large images for icons or splash screens. Icons and splash screens are often the first things that users see when they launch process and make your app feel sluggish.

7. use lazy loading:

using lazy loading is a technique that allows you to load images or other resources only when they’re needed. This can help to reduce flutter app size and even app performance is increased.

Difference between Axios and Fetch in making HTTP Request

0
Different Between Axios & fetch
Different Between Axios & fetch

Hi Guy’s Welcome to Proto Coders Point, In this article let’s check out the difference between the most commonly used http module/library i.e. axios and fetch.

What is Axios ?

Axios is basically a Nodejs Library/Module, which is been used to make HTTP requests, It provide a various types of HTTP requests, such as GET, POST, PUT, DELETE etc. Axios is used to fetch data from external servers.

To use Axios in NodeJS we must install the library and then import it where required

npm install axios

How to use Axios in NodeJS

Once Nodejs Axios library is installed, you need top import it into your nodeJS. Below is snippet code for better understanding:

const axios = require('axios');

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

What is fetch?

fetch function is an in-built global function in nodejs, That helps us in making asynchronois HTTP requests and handle responses.

To use fetch in nodejs you need to import the ‘node-fetch‘ module, and then make http calls like GET or POST method. Below is a code snippet example

const fetch = require('node-fetch');

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Difference Between Axios & Fetch

Here are some key differences between the Axios & Fetch:

1. Syntax and ease of use:


Axios: Axios provides a simplist way in making HTTP requests. The make advantage of using Axios to make http call is it uses promises which make it a higher level of abstraction, and make the code clean and easily understandable. Syntax & code example is above.


Fetch: Fetch is a in-built module of web API in any modern Web browsers that provides a native way to make HTTP requests. Syntax & code example is above.

2. Browser support:


Axios: Axios library is fully supports on any the browsers and even if the website is loaded into old version of browser it works perfect fine.


Fetch: While the fetch function is commonly supported by modern web browsers, it may necessitate the use of a polyfill or transpiler in order to function correctly in older browser versions.

3. Request and response handling:


Axios: Axios provides in-built feature to make http request and response interceptors, which helps developer to easily allow to modify any requests or responses that is made to API hit. It also supports automatic transformation of request and response data, such as JSON parsing or serialization.


Fetch: Fetch is an lower-level API as it does not have any built-in interceptors with it. develoepr need to manually handle all the request and response modifications. It also requires additional steps to parse or serialize data.

4. Error handling:


Axios: Axios has built-in error handling and automatically rejects the promise on HTTP error status codes (e.g., 404 or 500). It also allows you to define global error handling for all requests.


Fetch: Fetch does not reject the promise on HTTP error status codes by default. You need to check the response status manually and handle errors accordingly.

5. Cross-origin requests:


Axios: Axios supports cross-origin requests by default and handles CORS (Cross-Origin Resource Sharing) headers automatically.


Fetch: Fetch also supports cross-origin requests but requires explicit handling of CORS headers and may involve additional configuration.

In summary, Axios provides a more user-friendly and feature-rich API for making HTTP requests. It offers better error handling, automatic data transformation, and built-in interceptors. Fetch, on the other hand, is a native browser API with a lower-level interface and requires more manual handling for certain tasks.

Flutter Neumorphism – 3D Button

0
Flutter Neumorphirm - 3D Button.
Flutter Neumorphirm - 3D Button.

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Article let’s learn How to Create Neuporphism button.

Neumorphism in Flutter

Flutter Neomorphism is an UI element that is created by applying Shadows to give a Elevation effect to any Widget.

Let’s Understand neumorphism with a container, Two opposite edges, On is in front of light source while another is opposite, This create a shadow on the other end of the container.

In this Article we will give a neumorphism effect to a container making it a 3D button in flutter.

Complete Source Code – Flutter Neumorphic Button

import 'dart:ui';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var darkColors = Color(0xFF000A1F);
  var lightColors = Color(0xFF5A86EA);
  var isPressed = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.indigo,
        body: Center(
          child: GestureDetector(
            onTapUp: (val){
              setState(() {
                isPressed = false;

              });

            },
            onTapDown: (val){
              setState(() {
                isPressed = true;
              });

            },
            child: AnimatedContainer(
              duration: Duration(milliseconds: 100),
              width: 200,
              height: 200,
              padding: EdgeInsets.all(20.0),
              decoration: BoxDecoration(
                color: darkColors,
                borderRadius: BorderRadius.circular(20.0),
                boxShadow: isPressed ? null : [
                  BoxShadow(color: Colors.white,offset: Offset(-3,-3),blurRadius: 10.0,spreadRadius: 3.0),
                  BoxShadow(color: darkColors,offset: Offset(3,3),blurRadius: 10.0,spreadRadius: 3.0)
                ],
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    isPressed ? lightColors : darkColors,
                    isPressed ? darkColors : lightColors
                  ]
                )
              ),
            ),
          ),
        )
    );
  }
}

So, In above flutter code, we have a square shaped AnimatedContainer at the center of the screen.

In the container widget we will use decoration: property with BoxDecoration to make the normal container a neumorphism container.

In BoxDecoration, We are using:

  • color: To give color to the container.
  • borderRadius: To give a Circular Radius to the container.
  • boxShadow: To Apply a meumorphism shadow effect to the container.
  • gradient: linear gradient from topLeft to bottonRight a light & dark color gredient effect.

That make a normal container a neumorphism container & then to give a click/onTop feel I have Simply wrapped the AnimatedContainer with GestureDetector & make few changes in color when user tap by using onTapUp() & onTopDown() methods.

Video Tutorial

Blur Background in flutter using BackdropFilter widget

0
blur background in flutter using backdropfilter

Hi Guy’s Welcome to Proto Coders Point, In this flutter article we will learn how to Blur a background in flutter by using "BackdropFilter" widget with imageFilter.blur property.

Code to Blur Background in flutter

import 'dart:ui';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: [
            // Background widget
            Image.asset(
              'assets/background_image.jpg',
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            ),

            // BackdropFilter to blur the background
            BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
              child: Container(
                color: Colors.black.withOpacity(0.5), // Adjust the opacity as needed
              ),
            ),

            // Content widget
            Center(
              child: Text(
                'Hello, World!',
                style: TextStyle(fontSize: 30, color: Colors.white),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Output

blur background in flutter using backdropfilter

The Above Code Explanation to blur a background in flutter

  1. Use a Stack widget as root widget. By using Stack widget we can stack multiple widget on top on each other.
  2. Add a Image widget as a first child of the Stack. This will be backgroud widget that will get blurred.
  3. Use BackdropFilter widget. The BackdropFilter widget applies a filter to the widget that come behind it.
  4. Set the filter property of the BackdropFilter widget to the ImageFilter.blur constructor, specifying the amount of blur you want. You can adjust the sigmaX and sigmaY values to control the blur intensity.

Video Tutorial