FlotaingActionButton Widget and Attributes

FlotaingActionButton Widget and Attributes

ยท

2 min read

The FloatingActionButton widget in Flutter is a circular button typically placed in the bottom-right corner of the screen. It's commonly used to trigger the most important action in the application, such as adding a new item or navigating to a primary destination.

Attributes:

  1. onPressed (Function):

    • The callback function that is called when the button is pressed. This attribute is required.
  2. child (Widget):

    • The widget to be displayed inside the button. It's typically an Icon or Text widget.
  3. tooltip (String):

    • The tooltip message to be displayed when the user long-presses the button. It's an optional attribute.
  4. backgroundColor (Color):

    • The background color of the button. It defaults to the accent color of the current theme if not specified.
  5. foregroundColor (Color):

    • The foreground color of the button, which affects the color of the child widget. It defaults to white if not specified.
  6. elevation (double):

    • The elevation of the button, which affects its shadow. The default value is 6.0.
  7. shape (ShapeBorder):

    • The shape of the button. It defaults to a circular shape.
  8. heroTag (Object):

    • An optional tag for identifying the button in hero animations. If omitted, a unique tag will be generated automatically.

Example:

import 'package:flutter/material.dart';

class FloatingActionButtonExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FloatingActionButton Widget Example'),
      ),
      body: Center(
        child: Text('Press the FloatingActionButton'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add your action here
          print('FloatingActionButton pressed');
        },
        child: Icon(Icons.add),
        tooltip: 'Add',
        backgroundColor: Colors.blue,
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: FloatingActionButtonExample(),
  ));
}

Explanation:

  • In this example, a FloatingActionButton widget is placed inside a Scaffold widget.

  • The onPressed attribute is set to a callback function that prints a message when the button is pressed.

  • The child attribute is set to an Icon widget with the "add" icon to represent the button.

  • The tooltip attribute is set to "Add" to provide a tooltip message when the button is long-pressed.

  • The backgroundColor attribute is set to Colors.blue to specify the background color of the button.

  • When you run this code, you'll see an app bar with a title and a centered text widget. Pressing the floating action button will print a message to the console.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย