Home Blog

How to create 3 dot popup menu item on AppBar Flutter

0
pop up menu button item
pop up menu button item

Hi Guys, Welcome to Proto Coders Point, In this Article we will learn how to create popup menu in flutter appbar.

Final App – Example on Popup dropdown menu item in appbar

As you can see in the above app screenshot, I have a menu item on the app bar, Which contains 3 menus that a user can select ‘Setting‘, ‘Privacy policy‘, and a ‘Logout‘ menu.

How to create popup menu in flutter appbar

video tutorial

In Flutter we can easily create appbar menu by using ‘actions’ properties of flutter appbar. (To learn more about appbar visit official site here)

appBar: AppBar(
        centerTitle: true,
        title: Text("App Dropdown Menu"),
        actions: [

               //list of widget you want to show in appbar

          ],
      ),

Easiest way to add 3 dot popup menu in appbar

The simplistic way to add 3 dot popup menu is by using flutter Appbar actions:[] properties.

A Appbar actions properties is a array that accept list of widget, In our case we are using PopupMenuButton to show PopupMenuItem.

Here is an snippet code of PopupMenuButton

 appBar: AppBar(
        centerTitle: true,
        title: Text("App Dropdown Menu"),
        actions: [
                 //list if widget in appbar actions
                PopupMenuButton(
                            icon: Icon(Icons.menu),  //don't specify icon if you want 3 dot menu
                            color: Colors.blue,
                            itemBuilder: (context) => [
                                     PopupMenuItem<int>(
                                                     value: 0,
                                                     child: Text("Setting",style: TextStyle(color: Colors.white),),
                                        ),
                            ],
                   onSelected: (item) => {print(item)},
        ),

        ],
),//appbar end

Explanation of above snippet code

Above App bar in actions properties which accept widgets, there we are placing PopupMenuButton Widget, In PopMenuButton there is a required property i.e. itemBuilder.

itemBuilder(): is a context that builds list of PopupmenuItem.

PopupMenuItem widget has 2 propeties i.e. value & child

value: is used to set an Id to a menuItem, so that when the user selects the menu item, we can detect which menu item was clicked by the user.

child: this is just to show a widget like Text in the particular menuItem.

How to use onTap or onPressed in PopupMenuItem

In PopupMenuButton there a property called onSelected: (value), which keep track of which item is been selected by the user from menuItem.

Here is an explanation on the same

flutter dropdown menuitem appbar

Complete Source Code of Flutter Appbar with Menu Items

LoginPage.dart

import 'package:flutter/material.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("This is Login Page"),
      ),
    );
  }
}

SettingPage.dart

import 'package:flutter/material.dart';

class SettingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("This is Setting Page"),
      ),
    );
  }
}

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/LoginPage.dart';
import 'package:flutter_app_simple/SettingPage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("App Dropdown Menu"),
        actions: [
          Theme(
            data: Theme.of(context).copyWith(
                textTheme: TextTheme().apply(bodyColor: Colors.black),
                dividerColor: Colors.white,
                iconTheme: IconThemeData(color: Colors.white)),
            child: PopupMenuButton<int>(
              color: Colors.black,
              itemBuilder: (context) => [
                PopupMenuItem<int>(value: 0, child: Text("Setting")),
                PopupMenuItem<int>(
                    value: 1, child: Text("Privacy Policy page")),
                PopupMenuDivider(),
                PopupMenuItem<int>(
                    value: 2,
                    child: Row(
                      children: [
                        Icon(
                          Icons.logout,
                          color: Colors.red,
                        ),
                        const SizedBox(
                          width: 7,
                        ),
                        Text("Logout")
                      ],
                    )),
              ],
              onSelected: (item) => SelectedItem(context, item),
            ),
          ),
        ],
      ),
      body: Container();
    );
  }

  void SelectedItem(BuildContext context, item) {
    switch (item) {
      case 0:
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => SettingPage()));
        break;
      case 1:
        print("Privacy Clicked");
        break;
      case 2:
        print("User Logged out");
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => LoginPage()),
            (route) => false);
        break;
    }
  }
}


Output

menu item in flutter

Icons in flutter – font awesome flutter

0
Icons in flutter
font awesome icon example

Hi Guys, Welcome to Proto coders point, In this flutter tutorial we will implement font awesome icons a package that provides more than 1500+ icons in flutter page UI design.

This font awesome icon flutter package is very useful because with few lines of code we can easily use free icons in our flutter application.

To view all the available and free icons provided by fontawesome just visit fontawesome.com & make use of the search box to discover/find out your desired icon fr the flutter app.

so lets begin with implementation of flutter awesome fonts package.

Adding icon package in your flutter app

1. Create/Open a flutter project

Offcourse you need to create/open a new flutter project in your favorite IDE, android studio or vscode.

In my case, my favorite IDE is android studio – so i will be working with it.

if flutter plugin not install in your android studio check this Install Flutter plugin & flutter sdk in android studio.

create new project IDE -> New -> New Flutter Project -> give a name to flutter project -> Next -> finish.

your flutter will be created.

2. Add font_awesome_flutter dependencies

Now once your flutter project is read and completed with the gradle build process, then now it time to add the dependencies.

then open pubspec.yaml file, that you will find in project secton on the left side of your IDE.

and app icon package dependencies

dependencies:
  font_awesome_flutter: ^9.0.0

3. Import it where icons are required from font awesome

then after adding the dependenies in your flutte project now to use it in your dart code you just need to import the font_awesome_flutter.dart library file.

import 'package:font_awesome_flutter/font_awesome_flutter.dart';

4. Snippet code – How to use FaIcon widget in a flutter

FaIcon
(

FontAwesomeIcons.googlePay,
color: Colors.deepOrange,
size: 35,

)

Complete Source code – font awesome icons example 1

This icon package provide more than 1500+ free icons that you can use in your flutter project.

Based on font awesome, Include all free icons:

  • Regular Icons.
  • Solid Icons.
  • Brand icons.

Source code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Font Awesome Icons")
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Text("Few Free Icon from Font Awesome Flutter package",textAlign:TextAlign.center,style: TextStyle(fontSize: 30),),
            SizedBox(height: 20,),
            //brand Icons
            Text("Brand Icons",textAlign: TextAlign.start,style: TextStyle(fontWeight: FontWeight.bold,fontStyle:FontStyle.italic,fontSize: 20),),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FaIcon(FontAwesomeIcons.googlePay,color: Colors.deepOrange,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.facebook,color: Colors.blue,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.github,color: Colors.black,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.twitter,color: Colors.blueAccent,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.aws,color: Colors.deepOrange,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.pinterest,color: Colors.red,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.wordpress,color: Colors.deepPurple,size: 35,),
              ],
            ),
            SizedBox(height: 25,),
            //Regular Icons
            Text("Regular Icons",textAlign: TextAlign.start,style: TextStyle(fontWeight: FontWeight.bold,fontStyle:FontStyle.italic,fontSize: 20),),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FaIcon(FontAwesomeIcons.smile,color: Colors.green,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.laugh,color: Colors.blue,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.dollarSign,color: Colors.green,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.accessibleIcon,color: Colors.red,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.iceCream,color: Colors.pink,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.plane,color: Colors.brown,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.peopleArrows,color: Colors.deepPurple,size: 35,),
              ],
            ),

            SizedBox(height: 25,),
            //Regular Icons
            Text("Solid Icons",textAlign: TextAlign.start,style: TextStyle(fontWeight: FontWeight.bold,fontStyle:FontStyle.italic,fontSize: 20),),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FaIcon(FontAwesomeIcons.virus,color: Colors.red,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.mask,color: Colors.blue,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.dollarSign,color: Colors.green,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.atom,color: Colors.red,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.truckMonster,color: Colors.black,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.bacteria,color: Colors.red,size: 35,),
                SizedBox(width: 15,),
                FaIcon(FontAwesomeIcons.arrowAltCircleRight ,color: Colors.deepPurple,size: 35,),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Font awesome icon output

font awesome icons example
font awesome icons example

This flutter icons package provide lots of regular & also many brand icons that you are allowed to use freely, such as:

  • google play icon,
  • Amazon AWS icon,
  • facebook icons

and much more like regular icons such as:

  • home Icon,
  • setting icon
  • back arrow icon,
  • forward arrow icon
  • menu icon & much more using this package.

Bottom Navigation Bar Font Awesome Icons Example 2

code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Font Awesome Icons")
      ),
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: FaIcon(FontAwesomeIcons.home),label: "Home"),
          BottomNavigationBarItem(icon: FaIcon(FontAwesomeIcons.idBadge),label: "Profile"),
          BottomNavigationBarItem(icon: FaIcon(FontAwesomeIcons.cog),label: "Setting"),
        ],
      ) ,
    );
  }
}

Output

viewFlipper in android studio – Image Slider example using view flipper

0
viewflipper android
viewflipper android

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will learn & implement android viewFlipper with example.

What is viewflipper in android?

ViewFlipper in android is a layout view that accept more then one view (like Imageview,TextView or any other layout vew) but display only one view at a time & thus we can use viewflipper to transition from one view to another with proper animation effect while switching smoothy between view in view flipper.

In Android, view flippers are mostly used as automatic image slider in android androidhive, the easiest way to show image slider to the app users.

android ViewFlipper Example

image slider using viewflipper android

Note: Android viewFlipper & ViewSwitcher both work same but the difference is:
viewSwitcher: can’t home more then 2 view child.
viewFlipper: can hold two or more child view at a same time.

Basic ViewFlipper XML code Example

In below xml snippet code you see i have view Flipper that has 3 view as a child of it, you can add as many view you want to flip.

<ViewFlipper
       android:id="@+id/ViewFlipper1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

       <!-- You can add as many view you want to flip -->
       <!-- I have created 3 TextView under viewFipper -->
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="This is TextView 1"/>

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="This is TextView 2"/>

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="This is TextView 3"/>

   </ViewFlipper>

Steps to Implement ViewFlipper in android

Time needed: 2 minutes.

Below i step by step process to adding view flipper android

  1. Create View Flipper reference

    create a reference object of view flipper class by using findViewById().

    ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.ViewFlipper1);

  2. Declare Animation object

    Then Declare 2 Animation object using Animation Utilities & LoadAnimation default Animation effect.

    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);

  3. Set in-Animation

    Now set In-animation to flipper using viewflipper.setInAnimation(in);

    viewFlipper.setInAnimation(in);

  4. Set Out-Animation

    Now set out-animation to flipper using viewflipper.setOutAnimation(out);

    viewFlipper.setOutAnimation(out);

  5. set timer to change view

    set the flip Interval timer to change to next view.

    viewFlipper.setFlipInterval(3000); //in millisecond

  6. finally

    Use autoStart or manually startFlipping

    simpleViewFlipper.setAutoStart(true);
    simpleViewFlipper.startFlipping();

Let’s look into some useful Method of ViewFlipper

Here are some view Flipper method that are used to manage the vie

1. startFlipping(): Start the timer to cycle through view flipper child views, you can call this method on events such as button click or some other event.
Eg: Start cycler of view flipper android

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
viewFlipper.startFlipping();   // start the view cycle


2. stopFlipping(): used to stop flipping of child view, when we no longer need to see the flip view of the child layout. call stop flipping method on button press or any other event.

Eg:

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
viewFlipper.stopFlipping();   //stop it 

3. setFlipInterval(milliseconds): The time before switching to next child view in milliseconds.

Eg: as you see we have set the flip interval to 2 second : 2000 milliseconds before switching to next view.

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
viewFlipper.setFlipInterval(2000);  //interval of 2 secends

or you can set Interval directly through xml

 <ViewFlipper
        android:id="@+id/simpleViewFlipper"
        android:layout_width="match_parent"
        android:flipInterval="2000"
        android:layout_height="wrap_content">
 </ViewFlipper>

4. setAutoStart(boolean): This method will automatically call startFlipping() method. when the app loads.

Eg:

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
viewFlipper.setAutoStart(true);

or else directly start from xml using autoStart

    <ViewFlipper
        android:id="@+id/simpleViewFlipper"
        android:layout_width="match_parent"
        android:autoStart="true"
        android:layout_height="wrap_content">
    </ViewFlipper>

5. isAutoStart(): used to check if the viewflipper is in autoStart mode. This return boolean type value either true or false.
it is true if the view get automatically start else return false.

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
       
       if(viewFlipper.isAutoStart()){
            // if true
        }else{
            // if false
        }

6. isFlipping(): used to check if viewFlipping is flipping or no. This method returns either true or false

Eg:

ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
Boolean isFlipOn = viewFlipper.isFlipping();

7. showNext(): used to manually switch to next child view of viewfliper on some event like button pressed.

Eg:

 ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
      
 btnNext.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               viewFlipper.showNext(); //go to next child view on button click
           }
       });

8. showPrevious(): used to go back to previous child view

Eg: when button press go back to previous child view

 ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);
       
 btnPrevious.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               viewFlipper.showPrevious();  // go to previous child
           }
       });

9. LoadAnimation(context,anim effect id): Used to define a Animation effect using AnimationUtilities.

Eg:

       // Declare in and out animations and load them using AnimationUtils class
        Animation outAnim = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
        Animation inAnim = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);


10. setInAnimation(inAnim) & setOutAnimation(outAnim): used to set Animation effect to viewflipper which switching between child.

       // set the animation type to ViewFlipper
        viewFlipper.setInAnimation(inAnim);
        viewFlipper.setOutAnimation(outAnim);

11. addView(View child): Using addView you can easily add new child view to viewFlipper at RunTime of your android app dynamically.

Eg:

       ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.simpleViewFlipper);

        TextView t1 = new TextView(this);
        t1.setText("This is Set text addview view flipper example");
        
        ImageView imv2 = new ImageView(this);
        imv2.setImageResource(R.drawable.image1);

        //adding new view at runtime to viewflipper
        viewFlipper.addView(t1);
        viewFlipper.addView(imv2);

Complete Source Code on ViewFlipper in android

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    
    <ViewFlipper
        android:id="@+id/viewFlipperId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ViewFlipper>


    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="150dp"
        android:background="#005"
        android:text="NEXT"
        android:textColor="#fff"
        android:textStyle="bold" />

</LinearLayout>

MainActivity.java

package com.example.viewflipper;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MainActivity extends AppCompatActivity {

    private ViewFlipper simpleViewFlipper;
    Button btnNext;
    
    //array list of images from drawable
    int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5,R.drawable.image6};     // array of images
    
    ImageView imageview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnNext = (Button) findViewById(R.id.buttonNext);
        simpleViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipperId);

       //create imageview view and add the view to viewflipper
        for(int i = 0;i<images.length;i++){
            imageview = new ImageView(this);
            imageview.setImageResource(images[i]);
            simpleViewFlipper.addView(imageview);
        }



        // Declare in and out animations and load them using AnimationUtils class
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);


        // set the animation type to ViewFlipper
        simpleViewFlipper.setInAnimation(in);
        simpleViewFlipper.setOutAnimation(out);

        simpleViewFlipper.setFlipInterval(1000);
        // set auto start for flipping between views
        simpleViewFlipper.setAutoStart(true);
        simpleViewFlipper.startFlipping();

        btnNext.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                // show the next view of ViewFlipper
                simpleViewFlipper.showNext();
            }
        });
    }
}

output – android viewFlipper Example

viewflipper image slider
View Flipper android

Animation using Flutter Lottie animations

0
flutter lottie animation example

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will talk about a flutter package called ‘Lottie‘ that helps us to load animation files that are in JSON format.

A Lottie animation – for flutter

The Lottie is a website that provides some free animation image files in JSON format that we can add in our flutter application to display pre-built animation like ‘Lottie animal crossing’ as shown below.

lottie animal crossing

A Lottie is a pre-built Animation that is in JSON format, For the JSON file, we can simply add it in our flutter assets folder & use them to display Lottie animation in the flutter app.

The Flutter Lottie is a package library that parses Adobe After Effect animation file exported in JSON file & renders them natively on mobile device app.
It works greatly and smoothly on Windows, Web, Linux, iOS, and Android Devices.

Video Tutorial

How to install/add flutter Lottie package in flutter project

1. Add lottie dependence

In your flutter project you will find a file by name pubspec.yaml open it and under dependencies section add the library.

dependencies:
  lottie: ^1.0.1

after adding new dependencies just click on pub get button

2. Import the lottie dart file

Now once you have added the lottie dependencies now you can use it anywhere in your flutter project.

then, to use it you just need to import lottie.dart package in your dart file.

import 'package:lottie/lottie.dart';

3. Download animated json file from Lottie files website

Now Visit https://lottiefiles.com/ and download your choice json animation file from lottiefiles.com

4. Create a Assets folder to store lottie animation json file

Now create a new flutter assets folder in your project and give the access to it in pubspec.yaml so that your flutter project can access the folder

if you are new to it refer below screenshot

Then as you can see I have created the folder ‘ assets/lottieJSON/….’ in which I have copied the downloaded json animation file from lottiefiles.com and then in pubspec.yaml file i have added the file path to the assets directory.

5. Snippet code to use Lottie widget flutter

Load json animation from assets folder

Lottie.asset(
                'assets/lottieJSON/animal_crossing.json',
                width: 200,
                height: 200,
                fit: BoxFit.cover
            ),

Loading animation json file from network URL

Here is a url of lottie moon christmas offering json animation

Lottie.network(
                "https://assets3.lottiefiles.com/packages/lf20_jaejabqz.json",
                width: 200,
               height: 200,
              fit: BoxFit.cover
            ),

Loading animated json file from zip file

Lottie.asset(
                "assets/lottieJSON/christmas.zip",
                width: 200,
                height: 200,
                fit: BoxFit.cover
            ),

Output of above Lottie widget

Flutter Logger – How to print log messages in flutter.

0
how to log in flutter
flutter logger library

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will cover flutter logger & how to log data in a flutter to help developers in debugging & improving projects for long-term maintenance.

Please note that in this flutter tutorial we will not cover logging in file or logging to remote service.

What is Logger – flutter?

A logger object is used to log/show messages on the IDE console Logcat window.
In Flutter, logging is the most important & useful feature provided that helps developers track, trace, find out the error log & debug logger error.

How to var log message in flutter?

Generally logging messages in flutter can be done using 2 ways

1. Using stdout & stderr


Generally printing a message on the console screen is done using the print() method by importing ‘dart:io’ & by invoking stdout & stderr.

Eg:

         stdout.writeln("This log is using stdout");
         stderr.writeln("This log is using stderr");


Output on Console

Using Print() method Example

print("This Message using Print method");

Suppose, the log message or error log message is long the android just ignores some of the log & print only half of it, In that case you can use ‘debugPrint()’ it will print whole list of log data error.

2. Other is using ‘dart:developer” log() function

This allows developer to include a bit more information in logging output messages.

So to use developer.log function in flutter print to console or devtool, you need to just import ‘dart:developer’ as devlog & now use it as shown below ( devlog.log(“This is Log message from developer log method”); )

import 'dart:developer' as devlog;

void main() {
  
 devlog.log("This is developer log func message",name:'MyLog');
  
}

output: developer.log console log will only be show in devTool

So now you have seen above log method are default dart logs
Here i have found out best flutter logger library that help in printing different kind of logs on console.

Best Flutter Library to log message on console

Flutter Logger Library

Flutter Logger library is very helpful for developer because it help usin printing log message on console n beautiful format.

We all use default log messages to print some statements on the console, as shown above, but they get missed & are difficult to find & might not even see them.

How to use flutter logger library

Learn more obout Logger from Official site

1. Add dependencies

Open pubspec.yaml > under dependenices section add logger: ^1.0.0

dependencies:
  logger: ^1.0.0  #version might change
2. Import the logger dart class

Then to make use of logger flutter you need to import the logger.dart file where you are going to use them.

import 'package:logger/logger.dart';
3. Creating instance of logger class & Printing on the console

default logger instance

  final logger = new Logger();

Custom logger instance

Logger in flutter takes some of the properties that you can customize how your logger message will be displayed on the console screen.

final logger = new Logger(
    printer: PrettyPrinter(
      methodCount: 1,
      lineLength: 50,
      errorMethodCount: 3,
      colors: true,
      printEmojis: true
    ),
  );

Then now once your instance of Logger is been created now you can use the instance object name to print log on console, as shown below

          logger.v("Verbose Log");
          logger.d("Debug Log");
          logger.i("Info Log");
          logger.w("Warning Log");
          logger.e("Error Log");
          logger.wtf("What a terriable failure log");

There are various kinds of log message that you can use to print on the console such as Verbose log, Debug Log, Info Log, Warning Log, Error Log, as shown in the above snippet code.

Outputflutter logger example

Logger Example – flutter

Flutter Null Safety example – handle null exception

0
null safety in flutter
null safety in flutter

Hi Guys, Welcome to Proto Coders Point, so in this flutter tutorial blog article, will learn about flutter null safety with example.

What is null safety in dart?

A Flutter Null Safety feature is a secured way of developing a flutter application, In any programming language, a variable can have a value assigned to it or might be null.

// Eg: Snippet 

String name;  // is null
String firstname = "Rajat Palankar";  //has a value been assigned.

because in dart variable can be null & if a variable is null we cannot perform an action with it like, printing the null value on user screen or we cannot execute at string method to a null value & if we do so this may lead to null pointer exception & your flutter application will crash in run-time.
As shown in below Code and output Screenshot

Example without null safety flutter


#code

// Snippet Flutter Dart code 

class _MyHomePageState extends State<MyHomePage> {
  String name;  // null value
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(name),   // trying to print null # run time , null pointer exception
      )
    );
  }
}

Output example

Here you can see that when i tried to print null in text widget it showing Failed assertion – A non-null string must be provided.

flutter app without null safety

Flutter null safety enable

To solve null pointer exception flutter 2 came with null safety feature.

Set the minimum sdk constrant to 2.12.0 or higher & also check you have updated flutter version(flutter 2)

Then, if you want to use null safety dart then you need to enable null safety to do so, in your flutter project go to

Flutter Project > pubspec.yaml file

change sdk version >= 2.12.0

environment:
  sdk: ">=2.12.0 <3.0.0"   

and run flutter pub get

So now you have successfully enabled null safety in flutter project, now all of our datatype are by default “Not Nullable”

Not nullable means they requires some value to be assigned to them. A String, Int, or any date type must have some value.

Eg: 

int number = 15;

String name = " Proto Coders Point";

What if you want some datatype to be nullable

If in case, you want to make a datatype to be nullable then you need to add a question (?) mark to the datatype.

so in the above example, just by adding ‘?’ immediately after the data type, you can make it nullable which means Null is allowed.

Flutter null Safety Examples

  1. Null Safety Example 1
flutter null safety example
Null safety Example

Late Modifier to achieve null safety

Example without late modifier which gives you null safety error.

String name;   // null safety error
  
  @override
  void initState() {
    super.initState();

    name = "Rajat Palankar";
  }

The above code will give you a null safety compilation error because dart is not clever enough to understand that you have initialized the value to the variable afterwords.

Therefore, to future initialization or late initialization value to variable you can make use of “late modifier”, that tells compiler that value will be initialized later on.

what is late modifier?

In Flutter late keyword will lets you use non-nullable datatype. Now i dart 2.12 has add late modifier, late keyword is used in two case:

  • While migrating flutter project to null safety.
  • Lazy initializing of a variable.

Late keyword is used just to promise dart compiler that you are going to intialize the value to variable later on in future.

Note: if you don’t full fill as promised using late modifier then your flutte app will crash at runtime.

Late modifier example

late String name;  // here I am using late keyword before datatype to tell the compiler that I will initialize the value later

  @override
  void initState() {
    super.initState();

    name = "Rajat Palankar";   // as promised initializing is done here 

    print(name);   //now i can use the variable
  }