Floating Action button is one the most used action button in the modern applications. In this tutorial, we will explore a Flutter floating action button example by coding it.
First of all, we should be aware where we have to use flutter floating action button. It is frequently used to “add”, “refresh” or “share” the content. You are allowed to use anywhere where it makes sense. Please don’t use more than one FloatingAction button per screen.
Let’s start building Flutter Floating Action Button. Flutter FloatingAction Widget code is super simple. First, let me share how much code we need to create a basic floating action button in
floatingActionButton: FloatingActionButton( child: Icon(Icons.refresh), onPressed: _changeText, backgroundColor: Colors.red, foregroundColor: Colors.black, )
Yes, that is all the code required to develop a cool looking FloatingAction Button in Flutter.
Floating Action Button Properties
Flutter, by
- child: is used to
show what we wanna show inside this widget. We are using a refresh icon. - onPressed: is called when we press the button. I am calling a function to change the text.
- backgroundColor: is the main
color that floating action button adapts. - foregroundColor: change the foreground
color . We are using red as background and black as foreground color.
On the
_changeText() { setState(() { if (msg.startsWith('F')) { msg = 'I have learned FloatingButton'; } else { msg = 'Flutter FloatingButton Example'; } }); }
This is all you need to know from flutter floating action button example code. It is time to show you the complete code of this tutorial.
import 'package:flutter/material.dart'; void main() => runApp(MaterialApp(title: "FloatingButton", home: MainActivity())); class MainActivity extends StatefulWidget { @override _MainActivityState createState() => _MainActivityState(); } class _MainActivityState extends State { String msg = 'Flutter FloatingButton Example'; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.yellow, appBar: AppBar( title: Text('Floating Button'), ), body: bodyWidget(), floatingActionButton: FloatingActionButton( child: Icon(Icons.refresh), onPressed: _changeText, backgroundColor: Colors.red, foregroundColor: Colors.black, ), ); } bodyWidget() { return Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( msg, style: TextStyle(fontSize: 20, fontStyle: FontStyle.italic), ), ], ), ), ); } _changeText() { setState(() { if (msg.startsWith('F')) { msg = 'I have learned FloatingButton'; } else { msg = 'Flutter FloatingButton Example'; } }); } }
Flutter offers you different kind of buttons for different needs. I would advise you to go through all of them.
- Raised Button
- Popup Menu Button
- Flat Button
- Icon Button
- Drop down Button
- Button Bar