How to use an extended floating action button in Flutter

Flutter is a framework that has been in development since 2017. It allows developers to create applications for the web, mobiles, tablets, and desktops using the same code. It also helps developers build beautiful and efficient UIs for various applications.

Extended floating action button

Extended FAB stands for floating action button, an application design element that remains fixed in the screen area. The information it contains can change, or new elements can appear.

In Flutter, the FloatingActionButton.extended constructor allows us to build another button, which is derived from the base material of the floating action button. This is an example of an extended FAB in which the label is accompanied by text and an icon, increasing the user’s awareness. It’s especially effective for actions that get value from the label’s extra information, for example, the “Add Item” or “Send Message” buttons.

Attributes

The extended widget comes with several attributes that developers can customize to fit the needs of their applications:

  • label: This is a widget (preferably a text widget) explaining the functionality of the related button.

  • icon: This is an optional widget (generally an icon) that indicates/hints at what the button does.

  • onPressed: A callback function will be invoked when the button is pressed. This is an important step where the nature of the button or the key operation has to be described.

  • shape: This option enables the button to be any shape the user wants (round, rectangular, oval, or any other shape).

Example usage

Heres an example application that you can play around with to test the working of the extended floating action button. Press the "Run" button below to start the Flutter application.

Flutter usually takes around 100-120 seconds to run the application for the first time.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Extended FAB Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.deepPurple,
      ),
      home: const MyHomePage(title: 'Extended FAB Demo Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool showOptions = false;
  List<String> items = [];

  void toggleOptions() {
    setState(() {
      showOptions = !showOptions;
    });
  }

  void addItem() {
    setState(() {
      items.add('Item ${items.length + 1}');
    });
  }

  void deleteItem() {
    setState(() {
      if (items.isNotEmpty) {
        items.removeLast();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Container(
            margin: EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: BorderRadius.circular(8.0),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.5),
                  spreadRadius: 1,
                  blurRadius: 2,
                  offset: Offset(0, 1), // changes position of shadow
                ),
              ],
            ),
            child: ListTile(
              leading: CircleAvatar(
                child: Text(
                  items[index][0],
                  style: TextStyle(color: Colors.white),
                ),
                backgroundColor: Colors.blue,
              ),
              title: Text(
                items[index],
                style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500),
              ),
              trailing: IconButton(
                icon: Icon(Icons.delete, color: Colors.red),
                onPressed: () {
                  setState(() {
                    items.removeAt(index);
                  });
                },
              ),
            ),
          );
        },
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton.extended(
            onPressed: toggleOptions,
            label: Text('Extended FAB'),
            icon: Icon(Icons.add_alert),
            backgroundColor: Colors.deepPurple,
          ),
          SizedBox(height: 16.0),
          Visibility(
            visible: showOptions,
            child: Column(
              children: [
                FloatingActionButton(
                  onPressed: addItem,
                  tooltip: 'Add Item',
                  child: Icon(Icons.add_alert_outlined),
                ),
                SizedBox(height: 16.0),
                FloatingActionButton(
                  onPressed: deleteItem,
                  tooltip: 'Delete Last Item',
                  child: Icon(Icons.delete_rounded),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
Extended FAB in Flutter

Code explanation

  • Lines 105110: These lines define an extended floating action button (FAB) with a label, an icon, and an onPressed function. The button’s properties allow it to call any specified function when pressed. In addition to the extended FAB, Flutter supports FABs in different sizes, including large and small variations.

Conclusion

By leveraging the extended floating action button (FAB) in Flutter, developers can significantly enhance the functionality and user experience of their applications. This feature provides an excellent way to create more engaging and informative interfaces, making it a valuable addition to any developer's toolkit.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved