Home Blog Page 67

How to animate icons – animated icons in a flutter

0
Animated Icons
Flutter Animated Icon widget

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to use font awesome animated Icons class to show/display animated icons in a flutter.

Icons in flutter

In Flutter we have different kinds of Icons that we can use for free to create a beautiful app UI.

  1. Static Icons: In static there are 2 kinds of those are
    Material Icon: Icon(Icons.add,size:100);
    Cupertino Icon: Icon(CupertinoIcon.moon_stars,size:100);
    So with both this flutter static icons i.e. Material Icon and CupertinoIcon you can make use of 1000’s of icons for your flutter UI design.
  2. Animated Icons:
    Then secondly we have our font awesome animated icons that are a pre-defined set of animate Icons that we can use off.

Introducation to flutter animated Icons

In flutter, you can use awesome animated icons that show animation effects in icons while moving/changing from one icon to another icon & also back to the previous one.
The Flutter Animated Icon class is been used to create a simple icon transition between two icons in the flutter.

There are many pre-defined Animated Icons in the flutter class, that you can use to create a very beautiful user interface, so if the user clicks on an icon then it will be a transition to another icon.

A Good Example is a music player app that has a play-pause button.

Video Tutorial on Animated Icons In Flutter with Example

1. How to use animated icon widget & controller for it

Widget snippet code

AnimatedIcon(
              icon: AnimatedIcons.play_pause,
              progress: iconController,   // a animation controller is need to control icon animation
              size: 150,
              color: Colors.green,
            ),

Controller

late AnimationController iconController;  // make sure u have flutter SDK > 2.12.0 (null safety) as we are using late keyword

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

    //create an instance of Controller and define a duration of 1 second.

    iconController = AnimationController(vsync: this,duration: Duration(milliseconds: 1000));

   // the below code will perform forword animation then then after 1 sec reverse the animation transition
    iconController.forward().then((value) async {
      await Future.delayed(Duration(seconds: 1));
      iconController.reverse();
    });
  }

In the above controller code, we are creating an instance object of AnimationController i.e. ‘iconController & initializing its duration to 1 second.

Then immediatly we are giving a transition animation effect to icon, by using controller.forword() to change icon from play to pause & then after 1 second delay, we are again changing the animation back to normal by using controller.reverse().

2. OnTap on Icon to Play Transition animation

Animated Icon with GestureDetector widget

          GestureDetector(
              onTap: (){
                AnimateIcon();  // call below method to start icon animation
              },
            child: AnimatedIcon(
              icon: AnimatedIcons.play_pause,  //pre-defined icon // use any
              progress: iconController,   //attached animation controllder
              size: 150,
              color: Colors.green,
            ),
          ),

Method & Animation Controller

  late AnimationController iconController;  // make sure u have flutter sdk > 2.12.0 (null safety)

  bool isAnimated = false;

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

    iconController = AnimationController(vsync: this,duration: Duration(milliseconds: 1000));
  }

//method called when user tap on icon
void AnimateIcon{
    setState(() {
      isAnimated = !isAnimated;
      isAnimated ? iconController.forward() : iconController.reverse();
    });
  }

// good practice to dispose controller when not in use
  @override
  void dispose() {
    // TODO: implement dispose
    iconController.dispose();
    super.dispose();
  }

In Above snipper code, i have:-

A Variable type boolean ‘isAnimated = false’, used to keep track of Animation Transition state.

In initState(), I am creating an instance object of Animation Controller class with an animation duration of 1000 milliseconds i.e. 1 second, and then the controller object is connected to widget i.e. AnimatedIcon( progress: iconController); as you see above

Then there is a method void AnimateIcon() which is been called when AnimatedIcon is been pressed/onTap. In that method first, we are setting isAnimated to true or false.

Then Performing transition using iconController.forword() & iconController.reverse();

If isAnimated is true then perform forword transition & if isAnimated is false then perform reverse transition.

& finally a good practice is to dispose the controller when the app is been closed, so dispose the controller in void dispose @override method.

Flutter Animated Icons Example – Complete Source Code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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> with SingleTickerProviderStateMixin {
  late AnimationController iconController;  // make sure u have flutter sdk > 2.12.0 (null safety)

  bool isAnimated = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    iconController = AnimationController(vsync: this,duration: Duration(milliseconds: 1000));

    iconController.forward().then((value) async {
      await Future.delayed(Duration(seconds: 1));
      iconController.reverse();
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("App Dropdown Menu"),

        ),
        body: Center(
          child: GestureDetector(
              onTap: (){
                AnimateIcon();
              },
            child: AnimatedIcon(
              icon: AnimatedIcons.play_pause,
              progress: iconController,
              size: 150,
              color: Colors.green,
            ),
          ),
        )
    );


  }
  void AnimateIcon(){
    setState(() {
      isAnimated = !isAnimated; //if false then change it to true, likewise if true change it to false

      //if true then forword else reverse
      isAnimated ? iconController.forward() : iconController.reverse();
    });
  }

  @override
  void dispose() {
    // implement dispose
    iconController.dispose();
    super.dispose();
  }

}

Output

play pause animation  icon in flutter
play pause animation icon in flutter

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