In Flutter, the FloatingActionButton widget is a button that is typically placed in a Scaffold to represent the primary action in the application. It is often used for actions such as adding a new item, creating a new task, or any other primary action in the app. Here are some key attributes and properties of the FloatingActionButton:
Attributes and Properties:
onPressed: A callback function that is triggered when the button is pressed.
child: The widget to be displayed inside the button. It is often an Icon widget.
tooltip: A text that appears as a label when the user long-presses the button.
backgroundColor: The background color of the button.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FloatingActionButton Example'),
),
body: Center(
child: Text(
'Press the FloatingActionButton!',
style: TextStyle(fontSize: 18),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Handle button press
print('FloatingActionButton Pressed!');
},
child: Icon(Icons.add),
tooltip: 'Add Item',
backgroundColor: Colors.blue,
),
);
}
}
In this example, we have a Flutter application with a single screen (Scaffold) containing an AppBar, a Center widget with a text message, and a FloatingActionButton. The onPressed callback for the FloatingActionButton is set to print a message to the console when the button is pressed. The child property is set to an Icon widget with the "add" icon from the Material Icons library. The tooltip provides a label for the button, and the backgroundColor sets the background color of the button.
Full Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FloatingActionButton Full Example'),
),
body: Center(
child: Text(
'Press the FloatingActionButton!',
style: TextStyle(fontSize: 18),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Handle button press
print('FloatingActionButton Pressed!');
},
child: Icon(Icons.add),
tooltip: 'Add Item',
backgroundColor: Colors.blue,
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
}
In this full example, we've added the floatingActionButtonLocation property to position the FloatingActionButton at the center of the screen. This property is optional, and you can choose the desired location based on your app's design.