Home Blog Page 67

Understanding Future, async & await in the flutter dart

0
why and when to use async await in flutter dart
why and when to use async await in flutter dart

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial we will learn what is async & await in flutter.

In order to understand flutter async & await in dart, first we need to learn synchronous vs asynchronous programming in dart & how it works.

synchronous vs asynchronous programming

  • synchronous: In simple words, When you execute code synchronously then you need to wait for it to finish task 1 before you move to task 2.
  • asynchronous: When you execute code asynchronously, then you can continue to execute the next task, no need to wait for the previous task to complete, but in case if task 1 & task 2 are related like, talk 2 get data from task 1 then you need to make use of async & await in a flutter.

Understanding async & await in flutter

We write code or a lines of code that takes very short amount of time to execute & give result

print(''Hello World');

for example we want to print text on console, as you see that it is a single line statement that takes about fraction of second to complete the task, but there are some code or task that need more time to get executed completly for example: loading a image or File from internet.

Here are some common asynchronous task:-

  1. Fetching data(image or file) over a network.
  2. Writing data to a database.
  3. Reading a huge list of file from internet.

Therefore, to perform the asynchronous operations in a dart programming language, we make use of the Future class & the async & await keyword in a flutter.

synchronous and asynchronous programming code example

synchronous programming

for better understanding lets look into how synochronous code works,

//snippet method

void Function(){

   //step 1
   print('Hello World');

   //step 2
   loadImage('url of image to load');

   //step 3
   print('Hello World');


}

When the above method is been called the step 1 gets executed immediately but step 3 executes only when the step 2 process is completely over/executed.

Suppose you have an image to be loaded in step 2 & due to an internet or network issue step 2 never get executed then you code will get stuck at step 2 and step 3 never gets executed until step 2 task is over.

Therefore, in synchronous method every thing works in a sync order/step by step process( The next task will not work until the current task is completed)

asynchronous programming

//snippet method

void Function() async{

   //step 1
   print('Hello World');

   //step 2
   async_loadImage('URL of image to load');  //if loading image take time then step 3 will execute and simultaneously step 2 will load at same time there is not wait.

//step 3
   print('Welcome to proto coders point');

}

So, if you have a method that load image & is a async method then, while the image been getting loaded, the step 3 will get executed, it simply means that the step 3 will not wait until step 2 complete the task.

flutter synchronous example

synchronous.dart code example

void main(){
  callMethods();
}

void callMethods(){
  method1();
  method2();
  method3();
}

void method1(){
  print('method 1 completed');
}

void method2(){
  print('method 2 completed');
}

void method3(){
  print('method 3 completed');
}

Here, its a synchronous code, which execute methods step by step process and the output will be in sequence order.

output

method 1 completed
method 2 completed
method 3 completed

Ok , then suppose if I add a sleep(duration) in method 2 then until sleep duration is not completed the execution of method 3 is still iin pending.

//snippet
void method2(){
  
  Duration wait3sec = Duration(seconds: 3);
  sleep(wait3sec); // sleep here for 3 second, then go forword
  print('method 2 completed');
}

Check out the screenshot of output

dart synchronous example

We have created artifically a sleep timer so that method 2 get paused for some time, but in real time application, the case might be different may be method 2 need time to load data or there might be network issue due to which data is loading slowly like downloading Imahe or files through Internet,

Therefore, if we use the synchronous method then until the image or file gets downloaded, method 3 will not execute, so this is the disadvantage of sync methods.

Flutter delayed method in flutter

Suppose you want to execute a piece of code after some duration then you can make use of async method i.e. Future.delayed(duration,(){});

void method2(){

  Duration wait3sec = Duration(seconds: 5);
  Future.delayed(wait3sec,(){
    print('Future delayed executes after 5 seconds ');
  });
  print('method 2 completed');
}

Now, if i add future delayed to above method 2() then the output will be something like this:

In above example, method 1,2,3 get executed immediatly there is not wait time, but in method 2 i have a future delayed that executed after some duration.

Why & When to use async & await in flutter

Below Example shows you what happens if async & await is not used.

import 'dart:io';

void main(){
  callMethods();
}

//note: that method 3 get data from the result of method 2, but method 3 get executed before method 2 return the result, due to which null get printed 
void callMethods(){
  method1();
  String result =  method2();
  method3(result);
}

void method1(){
  print('method 1 completed');
}

String method2(){

  Duration wait3sec = Duration(seconds: 2);
  String result;
  Future.delayed(wait3sec,(){
    result = 'data from method 2 ';

  });
  
  return result;
}

void method3(String data_from_method2){
  print('method 3 completed, received ${data_from_method2}');
}

output

method 1 completed
method 3 completed, received null

//note: method 3 get data from the result of method 2, but method 3 get executed before method 2 return the result, due to which null get printed.

So, as in above dart code, The method 3 display result as null because method 3 is called immediatly before method 2 return the data therefore string result is null & is passed to method 3 as null.

When to use async & await in flutter dart

Then as you see in the above example method 3 depended of the data that method 2 return, so to prevent null passed to method 3, we make use of async & await in dart.

Snippet Example how async await works in dart

import 'dart:io';

void main(){
  callMethods();
}

void callMethods() async{
  method1();
 String result =   await method2();
  method3(result);
}

void method1(){
  print('method 1 completed');
}

Future method2() async{

  Duration wait3sec = Duration(seconds: 2);
  String result;
  await Future.delayed(wait3sec,(){
    result = 'data from method 2 ';

  });

  return result;
}

void method3(String data_from_method2){
  print('method 3 completed, received ${data_from_method2}');
}

Explanation of above code.

dart async & await example flutter

So as you see the method3() needs data that method2 returns, so we are making use of async & await so that method 2 waits until it returns a result, and then once the result is available it is been passed to method 3. therefore method 3 runs successfully with null safety.

Output of above code

method 1 completed
method 3 completed, received data from method 2 

[Complete Source Code] Audio Player In Flutter – Assets Audio Player

0
audio player in flutter
audio player in flutter

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to play audio file by using assets_audio_player package that help you to play music from your project assets folder.

Video Tutorial

About Assets audio player package

This audio player flutter package is a very easy-to-use package that helps developers implement sound effects or play the audio files (mp3) from the assets folder, Can be used to develop apps that need some sound effects at a particular time (Eg: Game App).

Now with the latest update with the package, A new feature is been added i.e. we can play audio files from the network url or your own audio API & also listen to radio/Livestream audio music.

And if audio/music is playing & you exit the app, still the audio will be in background & show you Notification in notification bar you can also control the music that is playing from notification itself.

Feature of assets_audio_player package

You can play audio in various ways like

Assets File: Store audio in assets folder & play the audio by its path.

Network url: use exact url of audio file to play it.

Network livestream/radio url: use livestream url to play audio.

Various command/method to play with audio/sounds

  1. play()
  2. pause()
  3. stop()
  4. seek(Duration to)
  5. seekBy(Duration by)
  6. forword(speed)
  7. rewind(speed)
  8. next()
  9. previous().

There are more awesome feature that you can try ” to learn more about the assets audio player visit official site here

How to add & use assets audio player package in flutter

1. Add Dependencies

Open your flutter project & navigate to pubspec.yaml file & open it, then under dependencies add the audio player package.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.0
  assets_audio_player: ^3.0.3+3 #add this

then don’t forget to hit pub get button, it will download the package in your flutter project.

2. Add audio/music file in a folder

Create new directory in your flutter project Eg: assets/sound/ and copy/paste a music audio file in it. Check out below screenshot.

3. Declare the path of audio assets directory in pubspec.yaml

We need to specily the path of the audio directory, so that the app can read the files from the directory.

flutter:

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/sound/

Snippet Code of Assets Audio Player Package

Importing the package

You need to import the audio player package in dart file, where you want to use it.

import 'package:assets_audio_player/assets_audio_player.dart';

Creating an instance of AssetAudioPlayer

AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();  // this will create a instance object of a class

Now you can use audioPlayer object to set path of your audio file as shown below.

Open/initialize the audio file path

The below method create and initialize the audio file and play it automatically by default if you do not set autoStart: false.

audioplayer.open(
               Audio('assets/sound/bobbyrichards.mp3')
);

if you don’t want autoplay of audio then you can set property autoStart: false,
& There is one more useful property called showNotification:true.

audioplayer.open(
            Audio('assets/sound/bobbyrichards.mp3'),
            autoStart: false,
            showNotification: true
);

This above snippet code will play sound only when play() method get triggered when button is been pressed. and display a notification.

Play audio from network or from your Audio API

void playAudioNetwork() async{
    try{
      await player.open(
        Audio.network("URL PATH")
      );
    }catch(t){
      
    }
  }

Method used to control the audio player

play(): play the audio file.

pause(): pause the audio file.

stop(): completly stop the audio, then if played again then song start from beginning.

playOrPause(): if audio playing, then pause else play.

next(): play next song from the list of songs.

previous(): play prev song from the list of songs.

Jump to specific audio time length

if you want to play the music a particular time file or if you want to forword or rewind the audio at particular time in audio file.

audioPlayer.seek(Duration(seconds: 10));  // just to audio time 10

Forword or rewind the audio by specific time duration

audioPlayer.seekBy(Duration(seconds: 10));  // go 10 sec forword

audioPlayer.seekBy(Duration(seconds: -10));  /go -10 sec backwork

Learn more from offical site here.

Complete Source code Example on Assets Audio Player package

Output

Check the output on my youtube channel, Video tutorial is above

Audio player in flutter

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:assets_audio_player/assets_audio_player.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;
  bool showPlay = true;
  bool shopPause = false;
  
  AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();

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

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

    audioPlayer.open(Audio('assets/sound/bobbyrichards.mp3'),autoStart: false,showNotification: true);
    
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Playing Audio File Flutter"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.network("https://i.pinimg.com/originals/f7/3a/5b/f73a5b4b7262440684a2b5c39e684304.jpg",width: 300,),
              SizedBox(height: 30,),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                 InkWell(child: Icon(CupertinoIcons.backward_fill),onTap: (){
                   audioPlayer.seekBy(Duration(seconds: -10));
                 },),
                  GestureDetector(
                    onTap: () {
                      AnimateIcon();
                    },
                    child: AnimatedIcon(
                      icon: AnimatedIcons.play_pause,
                      progress: iconController,
                      size: 50,
                      color: Colors.black,
                    ),
                  ),
                  InkWell(child: Icon(CupertinoIcons.forward_fill),onTap: (){
                    audioPlayer.seekBy(Duration(seconds: 10));
                    audioPlayer.seek(Duration(seconds: 10));
                    audioPlayer.next();
                  },),
                ],
              ),

            ],
          ),
        ));
  }

  void AnimateIcon() {
    setState(() {
      isAnimated = !isAnimated;

     if(isAnimated)
       {
         iconController.forward();
         audioPlayer.play();
       }else{
       iconController.reverse();
       audioPlayer.pause();
     }


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

[100% Solved] Plugin ‘Dart’ is inCompatible, Plugin ‘Flutter’ is inCompatible

0
Plugin ‘Flutter’ is inCompatible

Hi Guys, Welcome to Proto Coders Point.

Ok, so recently I updated my Android Studio IDE version from 202.76.. to A.I-201.87.. and during updating process due to some network issue or any other reason.

The plugin which needs to be updated too such as dart, flutter, markdown, JetBrain marketPlace did not get updated due to which i faced an incompatible plugin version error as soon below.

  • Plugin Dart is incompatible (since build 202.766 > A.I-201.87433)
  • Plugin Flutter is incompatible (since build 202.766 > A.I-201.87433)
  • Plugin Gaugeis incompatible (since build 202.766 > A.I-201.87433)
  • Plugin JetBrains Marketplace is incompatible (since build 202.766 > A.I-201.87433)
  • PluginMarkdown is incompatible (since build 202.766 > A.I-201.87433)

Solution for incompatible plugin version

After some debugging, i found out 100% working solution & easy to do it.

You just need to update the incompatible plugin to latest version currently available.

Time needed: 1 minute

How to update plugins in android studio

  1. Go to File -> Setting

    A Setting window will get opened.

  2. Go to Plugins

    In the Setting window, go to the Plugins section on the left side of the window.

  3. Updated the Plugin

    Now, in the search box search for the plugin, you need to update or simply scroll down to find it.
    how to update plugin in android studio

  4. Restart the IDE

    Once you update all the plugin, it will ask you need to Restart IDE. Do it.
    Then the problem is solved successfully.

Error while merging dex archives – Solution 100% Working

0
error while merging dex archieve
enable multidex android

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will checkout & solve the common error that “error while merging dex archives”.

Video Tutorial to solve the same

The error says: DexArchiveMergerException

Cannot fit requested classes in a single file: com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:

so before looking into how to solve multi dex error, let’s learn basic about DEX(Dalvik Executable).

What is the dex file? Understanding Multidex in android

In Java, your code is converted from .java to .class file during compile time, so that our machine can understand the .class file but in android, the java code is compiled into DEX(Dalvik Executable) file so that our Android machine can understand it.

This article is for android/flutter developers who face DEX error “cannot fit requested classes in a single file: error while merging dex archieve“.

 error while merging dex archieve
error while merging dex archieve

The error itself says you, why you are facing “multi Dex error”, The number of methods references in a .dex file cannot exceed 64K (# 68563 > 65536).

A Single DEX file limits the number of methods referenced, A single DEX file is limited to 64K i.e. 65536, which simply means that you cannot create more than 65536 methods in a single DEX file(“cannot fit requested classes in a single file“).

usually, this DEX error occurs when a developer adds external android/flutter libraries,

So, sometimes by adding external libraries to your android/flutter projects, if your project merged app exceeds 65536 methods, than you will encounter a build error as mentioned above “error while merging dex archieve“.

Ways to enable multidex support in android studio project

Solution 1: Clean project and invalidate caches & restart

Once you add any external libraries in your android studio project always keep habit to clean project and invalidate cache restart.

Step 1: Menubar -> Build -> Clean Project then Rebuild project.

Step 2: Menubar -> Invalidate Caches/Restart.

Solution 2: Enable multidex for app over 64K methods

To enable multidex, if you are not using AndroidX, you need to add deprecated library in dependency

dependencies {
    implementation "com.android.support.multidex: 1.0.3 " //add this
    
}

By adding above multidex it will become a primary DEX file of your app.

if your minSdkVersion is set to 21 or higher, The Multidex is been enabled by default while creating new project, if not,

then do the followng steps:-

Step 1: modify Module level app/build.gradle

android {
    defaultConfig {
        applicationId "com.example.flutter_app_simple"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true //add this line
    }
}

dependencies {
    implementation "com.android.support.multidex: 1.0.3"  // add this line

}

Step 2: Add multidex in manifest <application> tag

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="androidx.multidex.MultiDexApplication" >  <!-- add this line -->
        ...
    </application>
</manifest>

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