Floating action button is a circular rounded button over application activity screen at bottom right side. There is always a Icon present inside the Floating action button which represents a certain task. To add the icon we would use flutter’s Material style Icon library which has thousands of free icons inside it. There is no need to set alignment of Floating action button over the screen it is automatically aligned for all Views. So in this tutorial we would Flutter Add Create Floating Action Button for Android iOS Example Tutorial. Floating Action Button is a widget part of Scaffold widget.
Contents in this project Flutter Add Create Floating Action Button for Android iOS Example Tutorial:
1. Open your project’s main.dart file and import material.dart package inside it.
1 |
import 'package:flutter/material.dart'; |
2. Create void main runApp() method and here we would call our main MyApp class .
1 |
void main() => runApp(MyApp()); |
3. Creating our main Root Parent class named as MyApp extends with StatelessWidget.
1 2 3 4 |
class MyApp extends StatelessWidget { } |
4. Creating a function named as calling() with a Print debug console message. We would call this function on Floating Action Button onClick event.
1 2 3 4 5 |
void calling() { print('Floating Action Button Clicked'); } |
5. Creating Widget Build area -> Material App widget -> Scaffold widget.
1 2 3 4 5 6 7 8 |
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( ) ); } |
6. Now first we would create AppBar widget to display AppBar on app screen.
1 2 3 |
appBar: AppBar( title: Text('Floating Action Button in Flutter') ), |
7. Now we would create body section of Screen and pass a Center -> Text widget inside it.
Note: If you want to display anything on main screen then all the widgets should be write inside body section.
1 2 3 |
body: Center( child: Text('Floating Action Button in Flutter', style: TextStyle(fontSize: 22),) ), |
8. Now finally we would make the FloatingActionButton widget after closing body part.
Note : FloatingActionButton widget is a part of Scaffold widget so we need to put it after closing body area.
1 2 3 4 5 |
floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () => calling(), ), ) |
9. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { void calling() { print('Floating Action Button Clicked'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Floating Action Button in Flutter') ), body: Center( child: Text('Floating Action Button in Flutter', style: TextStyle(fontSize: 22),) ), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () => calling(), ), ) ); } } |
Screenshots:
