Home Blog Page 2

Flutter File_Picker Package, Pick image, video, doc FilePicker Example

0
flutter file picker example - pick multiple files
flutter file picker example - pick multiple files

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial article, will explore how to pick files in flutter app.

File Picking in native platform like android & iOS is quite easy, but is even easier in flutter by using packages like file_picker.

So this flutter article is all about picking different types of files like Image, Video, Audio, pdf, doc etc.

Flutter File_Picker package

This package is very easily to use to pick file from native file explorer, it allows you to use file explorer of native platform to pick files , if support single & multiple file picking & also extension filtering is supported in selecting files.

Feature of file_picker

  • Invoke native platform OS picker to pick different types of files.
  • Developer can list type of extension a user can pick Eg: jpg, png, pdf etc.
  • Single and multiple file picks possible.
  • file type filtering (media,image,video, all type).

for more here.

Let’s Get Started with implementing file_picker in flutter app

Step 1: Create a flutter project & all file_picker dependencies

Create a new flutter project in your favourite IDE & add flutter picker package

open pubspec.yaml file & add file_picker

dependencies:
  file_picker:

then hit pub get or run flutter pub get command to download the package into your flutter project.


Step 2: import file_picker.dart

once you have added the dependencies package succesfully, to use file_picker you need to import it wherever required.

import 'package:file_picker/file_picker.dart';

Now, you can easily pick files in flutter app.


Properties of PickFiles class

PropertiesDescription
dialogTitle:Gives a Title to picker dialog
type:Define type of file to pick
Eg: FileType.any
FileType.image
FileType.video
FileType.audio
FileType.custom
[ should define allowedExtensions ]
allowedExtensions: [….]Allow only specific extensions file to be picker
Eg: allowedExtensions: [‘jpg’, ‘pdf’, ‘png’],
allowMultiple: true/falseallow Multiple files can be picked.

Pick Single File

If you want to pick single file in flutter, use below code

FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result == null) return;  // if user don't pick any thing then do nothing just return.

PlatformFile file = result!.files.first;
//now do something with file selected

Multiple file picking in flutter

Then, if you want to pick more then one file at once(multiple file picking), use below code.

 FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
 if (result == null) return;

 List<File> files = result!.paths.map((path) => File(path!)).toList();
// now do something with list of files selected/picked by a user

The files picked by a user is stored in List<File> array.


Pick particular type of file extensions

Sometimes, you want a user to only pick a particular type of file extensions, say jpg, png, pdf, doc etc in that case we can use 2 properties in pickFiles() class i.e

type: FileType.custom,
allowedExtensions: ['png','doc','pdf']
FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.custom,allowedExtensions: ['jpg','pdf']);
if (result == null) return;

PlatformFile file1 = result1!.files.first;

Now, native file explorer will only show the file with defined extensions


Get Full Details of picked file in flutter

So, now you have picked files using filepicker & now you want to read the details of file like name of file, size of file, type of file(extensions) & path of selected file. below is the code

FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result == null) return;


       PlatformFile file = result!.files.first;

       print('File Name: ${file?.name}');
       print('File Size: ${file?.size}');
       print('File Extension: ${file?.extension}');
       print('File Path: ${file?.path}');

Complete Source Code – Full File_Picker example in flutter

Note: I am using OpenFile package to open the user selected or picked file

main.dart

import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_file_picker/file_list.dart';
import 'package:open_file/open_file.dart';

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  String fileType = 'All';
  var fileTypeList = ['All', 'Image', 'Video', 'Audio','MultipleFile'];

  FilePickerResult? result;
  PlatformFile? file;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'Selected File Type:  ',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
                ),
                DropdownButton(
                  value: fileType,
                  items: fileTypeList.map((String type) {
                    return DropdownMenuItem(
                        value: type,
                        child: Text(
                          type,
                          style: TextStyle(fontSize: 20),
                        ));
                  }).toList(),
                  onChanged: (String? value) {
                    setState(() {
                      fileType = value!;
                      file = null;
                    });
                  },
                ),
              ],
            ),
            ElevatedButton(
              onPressed: () async {
                pickFiles(fileType);
              },
              child: Text('Pick file'),
            ),
            if (file != null) fileDetails(file!),
            if (file != null) ElevatedButton(onPressed: (){viewFile(file!);},child: Text('View Selected File'),)
          ],
        ),
      ),
    );
  }

  Widget fileDetails(PlatformFile file){
    final kb = file.size / 1024;
    final mb = kb / 1024;
    final size  = (mb>=1)?'${mb.toStringAsFixed(2)} MB' : '${kb.toStringAsFixed(2)} KB';
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('File Name: ${file.name}'),
          Text('File Size: $size'),
          Text('File Extension: ${file.extension}'),
          Text('File Path: ${file.path}'),
        ],
      ),
    );

  }

  void pickFiles(String? filetype) async {
    switch (filetype) {
      case 'Image':
        result = await FilePicker.platform.pickFiles(type: FileType.image);
        if (result == null) return;
        file = result!.files.first;
        setState(() {});
        break;
      case 'Video':
        result = await FilePicker.platform.pickFiles(type: FileType.video);
        if (result == null) return;
        file = result!.files.first;
        setState(() {});
        break;

      case 'Audio':
        result = await FilePicker.platform.pickFiles(type: FileType.audio);
        if (result == null) return;
        file = result!.files.first;
        setState(() {});
        break;
      case 'All':
        result = await FilePicker.platform.pickFiles();
        if (result == null) return;
        file = result!.files.first;
        setState(() {});
        break;
      case 'MultipleFile':
        result = await FilePicker.platform.pickFiles(allowMultiple: true);
        if (result == null) return;
        loadSelectedFiles(result!.files);
        break;
    }
  }

  // multiple file selected
  // navigate user to 2nd screen to show selected files
  void loadSelectedFiles(List<PlatformFile> files){
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => FileList(files: files, onOpenedFile:viewFile ))
    );
  }

  // open the picked file
  void viewFile(PlatformFile file) {
    OpenFile.open(file.path);
  }
}

file_list.dart

show list of user selected file in listview.

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';

class FileList extends StatefulWidget {
  final List<PlatformFile> files;
  final ValueChanged<PlatformFile> onOpenedFile;

  const FileList({Key? key, required this.files, required this.onOpenedFile})
      : super(key: key);

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

class _FileListState extends State<FileList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Selected Files'),
      ),
      body: ListView.builder(
          itemCount: widget.files.length,
          itemBuilder: (context, index) {
            final file = widget.files[index];

            return buildFile(file);
          }),
    );
  }

  Widget buildFile(PlatformFile file) {
    final kb = file.size / 1024;
    final mb = kb / 1024;
    final size = (mb >= 1)
        ? '${mb.toStringAsFixed(2)} MB'
        : '${kb.toStringAsFixed(2)} KB';
    return InkWell(
      onTap: () => widget.onOpenedFile(file),
      child: ListTile(
        leading: (file.extension == 'jpg' || file.extension == 'png')
            ? Image.file(
                File(file.path.toString()),
                width: 80,
                height: 80,
              )
            : Container(
                width: 80,
                height: 80,
              ),
        title: Text('${file.name}'),
        subtitle: Text('${file.extension}'),
        trailing: Text(
          '$size',
          style: TextStyle(fontWeight: FontWeight.w700),
        ),
      ),
    );
  }
}

Output

A new way to add Bottom Navigation Bar in flutter – Material you

0
flutter Navigation bar
flutter Navigation bar

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial will learn a new way to add bottom navigation bar in flutter by using flutter new Material You Navigation Bar Widget.

Important Note: To use new Material you navigation bar widget you need to switch to flutter master channel.

How to change flutter channel to master

  • Step 1: In your IDE Terminal run below command
    flutter channel master
  • Step 2: Then flutter update/upgrade Type
    flutter upgrade
  • Step 3: Restart your IDE

Thus, now you can use flutter material you navigation bar, Does it replace the aged flutter bottom navigation bar? let’s implement it and try it out now.

Let’s get started

Flutter material you Navigation bar widget

The first Material you widget i.e. “NavigationBar” is now been approved as new alternative way of adding bottom navigation bar into flutter app & its available to use in flutter master channel.

Therefore, flutter developers need to switch master channel to make use of material you in flutter.

Snippet Code

NavigationBar(
          height: 65,
          selectedIndex: 0,
          labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected,
          animationDuration: Duration(seconds: 2),
          onDestinationSelected: (index) {
            // callback to change between pages
          },
          destinations: const [
            // list of NavigationDestination Tabs
          ],
        ),

NavigationBar Properties

PropertiesDescriptionExample
destinations:[//list]List of Navigation Destination.
note: destination tab list must be two or more.
below
selectedIndex:Active tab of Navigation bar.
index starts from 0,1….n
selectedIndex : 2
onDestinationSelected:(index)Is a method is used to display pages of nav bar when user click on tab.example in below complete code.
backgroundColor:Change color of nav barbackgroundColor: Colors.blue.shade200,
height:specify height of nav barheight: 60
labelBehavior:We can hide or show or show only selected tab labelNavigationDestinationLabelBehavior.onlyShowSelected
NavigationDestinationLabelBehavior.alwaysHide
NavigationDestinationLabelBehavior.alwaysShow
animationDuration:animation effect during switching to another page or contentanimationDuration: Duration(seconds: 2),

NavigationDestination bottom Bar tab properties

Snippet Code

destinations: const [
            NavigationDestination(
              icon: Icon(Icons.access_time),
              label: 'Status',
              selectedIcon: Icon(Icons.access_time_filled),
            ),
            NavigationDestination(
              icon: Icon(Icons.call),
              label: 'Call',
              selectedIcon: Icon(Icons.call_outlined),
            ),
            
          ],
PropertiesDescriptionExample
iconset an icon to Navigation bar tabsicon: Icon(Icons.access_time)
selectedIconif nav tab is active will show this iconselectedIcon: Icon(Icons.access_time_filled)
labelText label to navigation bar tablabel: ‘Status’,

How to change Naivgation Bar label/Text Size, Color

To change Material You Navigation Bar labelTextStyle, you need to wrap NavigationBar with NavigationBarTheme & use data property with NavigationBarThemeData & then use labelTextStyle.

Check out below snipper code for better understanding

bottomNavigationBar: NavigationBarTheme(
        data: NavigationBarThemeData(
            labelTextStyle: MaterialStateProperty.all(
                TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
          ),
       ),
        child: NavigationBar(....)
 ),


Complete Source Code – Flutter Master Material You Navigation Bar

I am going to show 5 navigation tab.

flutter navigation bar

so let’s create 5 pages

  1. HomePage()
  2. CallPage()
  3. CameraPage()
  4. ChatPage()
  5. SettingPage()

HomePage.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 200,
          width: 200,
          child: Icon(Icons.home,size: 50,),
        ),
      ),
    );
  }
}

CallPage.dartt

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 200,
          width: 200,
          child: Icon(Icons.call,size: 50,),
        ),
      ),
    );
  }
}

Likewise create 3 more dart file as defined above and just change Icons

main code main.dart

import 'package:flutter/material.dart';
import 'package:navigationbar/call.dart';
import 'package:navigationbar/camera.dart';
import 'package:navigationbar/chat.dart';
import 'package:navigationbar/home.dart';
import 'package:navigationbar/setting.dart';

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  int tabselected = 0;
  final pages = [
    HomePage(),
    CallPage(),
    CameraPage(),
    ChatPage(),
    SettingPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: pages[tabselected],
      ),
      bottomNavigationBar: NavigationBarTheme(
        data: NavigationBarThemeData(
          indicatorColor: Colors.blue.shade200,
          backgroundColor: Colors.blue.shade500,
          labelTextStyle: MaterialStateProperty.all(
            TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
          ),
        ),
        child: NavigationBar(
          height: 65,
          selectedIndex: tabselected,
          labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
          animationDuration: Duration(seconds: 2),
          onDestinationSelected: (index) {
            setState(() {
              tabselected = index;
            });
          },
          destinations: const [
            NavigationDestination(
              icon: Icon(Icons.home),
              label: 'Home',
              selectedIcon: Icon(Icons.home_outlined),
            ),
            NavigationDestination(
              icon: Icon(Icons.call),
              label: 'Call',
              selectedIcon: Icon(Icons.call_outlined),
            ),
            NavigationDestination(
              icon: Icon(Icons.camera_alt),
              label: 'Camera',
              selectedIcon: Icon(Icons.camera_alt_outlined),
            ),
            NavigationDestination(
              icon: Icon(Icons.call),
              label: 'Call',
              selectedIcon: Icon(Icons.call_outlined),
            ),
            NavigationDestination(
              icon: Icon(Icons.settings),
              label: 'Setting',
              selectedIcon: Icon(Icons.settings_applications),
            ),
          ],
        ),
      ),
    );
  }
}

Related Article

Convex Bottom Bar Library

Bottom Navigation Bar with Fancy Animation effect

Flutter Curved Navigation Bar

Flutter battery level & state – Battery Plus package

0
Flutter Battery level & state - battery plus

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial will learn how to get battery state & battery level (percentage) of a mobile device in flutter.

Flutter Battery plus package

By using battery plus package in flutter we can easily access various information about the battery life of mobile device.

This package will give us battery level & Battery state:

Battery Level i.e. will get how much is battery percentage.

Battery State i.e will get BatteryState is FULL, CHARGING, DISCHARGING.


When is battery level checking useful in app

Sometimes, some important action in your app like background updates, let’s say the user doesn’t have enought battery percentage then this can lead to issues in performing background task like updates & if the phone is turning off during the process.

Depending on the battery level you can also maximize/minimize the performance, while the battery level is high/low, this can be especially used in games so if mobile device battery life is low then you can turn down the game performance.

Battery Plus can also be used to test how much the battery is been consumed during your flutter app is running.


Video Tutorial

Let’s get started with implementation

Step 1: Add battery plus dependencies

open pubspec.yaml file & under dependencies section add battery_plus package

dependencies:
  battery_plus:

& hit pub get to download the package.

Step 2: import battery_plus.dart

Now, once you have added the dependencies into your flutter project to use it, you need to import battery_plus.dart class.

How to use it

Create instance of battery class

//instantiate it
var battery = Battery();

now you can use the battery instance object to get battery information.

Access battery percentage/level

battery.batterylevel

Get State of Battery

The below code will be listening to any changes in BatteryState.

It will keep track of batteryState, Weather the mobile is in charging, discharged or battery full. There is a callback method that return enum values:

  1. BatteryState.charging.
  2. BatteryState.discharging.
  3. BatteryState.full.
battery.onBatteryStateChanged.listen((batteryState) {
//here batteryState is Enum that can return this values:
//BatteryState.charging.
// BatteryState.discharging.
// BatteryState.full.
});

Complete Source – Flutter Battery Plus Example

In this flutter example, we willl fetch battery percentage level & also keep track, when mobile is into charging & when is removed from charging(discharging) and it will also alert or update you when battery is FULL.

main.dart

import 'dart:async';

import 'package:battery_plus/battery_plus.dart';
import 'package:flutter/material.dart';

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  var battery = Battery();
  int level = 100;
  BatteryState batteryState = BatteryState.full;
  late Timer timer;
  late StreamSubscription streamSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBatteryPercentage();
    getBatteryState();
    timer = Timer.periodic(Duration(seconds: 5), (timer) {
      getBatteryPercentage();
    });
  }

  void getBatteryPercentage() async {
    final batteryLevel = await battery.batteryLevel;

    this.level = batteryLevel;

    setState(() {});
  }

  void getBatteryState() {
    streamSubscription = battery.onBatteryStateChanged.listen((state) {
      setState(() {
        this.batteryState = state;
      });
    });
  }

  @override
  void dispose() {
    streamSubscription.cancel();
    timer.cancel();
  }

  Widget BuildBattery(BatteryState state) {
    switch (state) {
      case BatteryState.full:
        return Container(
          child: Icon(
            Icons.battery_full,
            size: 200,
            color: Colors.green,
          ),
          width: 200,
          height: 200,
        );
      case BatteryState.charging:
        return Container(
          child:
              Icon(Icons.battery_charging_full, size: 200, color: Colors.blue),
          width: 200,
          height: 200,
        );
      case BatteryState.discharging:

      default:
        return Container(
          child: Icon(Icons.battery_alert, size: 200, color: Colors.grey),
          width: 200,
          height: 200,
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              BuildBattery(batteryState),
              Text(
                '${level} %',
                style: TextStyle(color: Colors.black, fontSize: 25),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

How to get rid of const keyword in static widget – Flutter Linter

0
add const modifier - remove const keyword

Hi Guys, Welcome to Proto Coders Point. If you have upgraded your flutter SDK version to 2.5.0 you might been seeing a warning been shown on every widget that use static data to add ‘const’ modifier at the beginning on the widget.

This is because by default we now have the flutter_lints rules applied.

Video tutorial to remove const keyword requirement in flutter

How to remove const keyword requirement in flutter code

It is a good practive using the const keyword on any data type or widget that use static data.

However if you fill like removing it, you can edit your analysis_options.yaml file and add the following:

open analysis_option.yaml file & under linter > rules disable prefer_const_constructor.

linter:
  rules:
    prefer_const_constructors : false

Then, after making prefer const constructors: false, you need to run a command in IDE terminal as below

dart fix

Flutter Floating Action Button – Expandable FAB Menu’s

0
flutter expandable menu item FAB
flutter expandable menu item FAB

Hi Guys, Welcome to Proto Coders Point. In this Flutter Tutorial will learn how to implement floating action button with popup FAB menu by using flutter_speed_dial package.

Floating Action Button(FAB)

In Flutter FAB is a round shape button that is floating at bottom right of your app mobile screen.

Flutter fab button is a primary action button event that a user commonly perform, but sometimes their can be some situation where user want to perform different event using fab menu in flutter.

In such case, developer can provide expandable FAB option, where when a user click on main FAB Button to expand floating action button spawns.

check out below fab expanding GIF Example

Here each fab menus can perform different event/action as defined.

Video Tutorial

Let’s get started

Flutter_Speed_Dial Package

The speed dial in flutter is animated transition of multiple Fab menu, which emits from a main FAB button when tapped/clicked (Expands multiple fab menu) & tapped again will absorb it back in it stack behind main fab button.

This floating button menu will have fab icons ( Animated Icons in FAB ) or ( Normal flutter icon) & a label to them.

Let’s start using flutter speed dial plugin into flutter app

Below are the steps to add speed dial package into flutter project as external library

Step 1: Adding flutter_speed_dial dependencies

Open pubspec.yaml file & add the fab button library under dependencies as shown below

dependencies:
  flutter_speed_dial:    # this line

Step 2: Run command to download above dependencies in flutter

Now, run a command in IDE terminal ‘flutter pub get’

C:\Android Studio Stuff\Flutter Project\fab_menu>flutter pub get

OR

hit pub get button on top pubspec.yaml file (Android Studio), this will download the package into your flutter project in external Libraries folder.

Step 3: import flutter_speed_dial.dart

Now, once dependencies is been added successfully, you need to import the plugin or package where you want to use it (say main.dart)

import 'package:flutter_speed_dial/flutter_speed_dial.dart';

Properities of speedDial widget

PropertiesUsage
animatedIcon:Define a animatedIcons, to show Fab Icon animation Eg: AnimatedIcons.menu_close.
backgroundColor:used to set a color to main FAb button. Eg: Colors.redAccent.
overlayColor:when FAB is open, overlay app content with light Color Eg: Colors.grey.
overLayOpacity:Set a opacity of overlayColor.
spacingGive some spacing between main FAB button & it’s child SpeedDialChild
spaceBetweenChildrenspacing between SpeedDialChild
closeManually:true or false, if set to false user need to tap back on FAB button to close it,
is set to true by default ( user can tap anywhere on screen to dismiss opened FAB button)
children:[]you can list of Speed Dial Child, that are menu of fab options
SpeedDial(
          animatedIcon: AnimatedIcons.menu_close,
          openCloseDial: isDialOpen,
          backgroundColor: Colors.redAccent,
          overlayColor: Colors.grey,
          overlayOpacity: 0.5,
          spacing: 15,
          spaceBetweenChildren: 15,
          closeManually: true,
          children: [
            // add multiple SpeedDialChild
          ],
        ),

Properties of SpeedDialChild widget

PropertiesDescription
child:Show a Widget of child FAB. Eg: Icon(Icons.share_rounded)
label:give label text
backgroundColor: used to set a color to main FAb button. Eg: Colors.blue
onTap():is a callBack, event to perform when user Tap on the SpeedDialChild fab menu
SpeedDialChild(
              child: Icon(Icons.copy),
              label: 'Copy',
                onTap: (){
                  print('Copy Tapped');
                }
            )


Complete Source Code – Expandable floating action button menu popup

Will have used WillPopScope to prevent user from exiting the app if floating action menu’sw are open.

So if FAB is open & user press back button FAB button should get closed.

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

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

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

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {

  ValueNotifier<bool> isDialOpen = ValueNotifier(false);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
          if(isDialOpen.value){
            isDialOpen.value = false;
            return false;
          }else{
            return true;
          }
      },
      child: Scaffold(
        floatingActionButton: SpeedDial(
          animatedIcon: AnimatedIcons.menu_close,
          openCloseDial: isDialOpen,
          backgroundColor: Colors.redAccent,
          overlayColor: Colors.grey,
          overlayOpacity: 0.5,
          spacing: 15,
          spaceBetweenChildren: 15,
          closeManually: true,
          children: [
            SpeedDialChild(
              child: Icon(Icons.share_rounded),
              label: 'Share',
              backgroundColor: Colors.blue,
              onTap: (){
                print('Share Tapped');
              }
            ),
            SpeedDialChild(
              child: Icon(Icons.mail),
              label: 'Mail',
                onTap: (){
                  print('Mail Tapped');
                }
            ),
            SpeedDialChild(
              child: Icon(Icons.copy),
              label: 'Copy',
                onTap: (){
                  print('Copy Tapped');
                }
            ),
          ],
        ),
        body: Container(
          alignment: Alignment.center,
          child: const Text("FAB Menu Example",style: TextStyle(fontSize: 30),),
        ),
      ),
    );
  }
}