Flutter FloatingActionButton – Switch Icons onPressed

Flutter FloatingActionButton – Switch Icons

Sometimes, it may be required that you change the icon present in FloatingActionButton.

In this tutorial, we will learn how to switch between two icons when you press on the FloatingActionButton.

In the onPressed() function of floatingActionButton, we shall write a logic to switch between the Icons.

Example: Swich Icons of FloatingActionButton onPressed()

In this example, we shall take an Icon variable named fab with some initial value. When you click on the floatingActionButton, onPressed() function is triggered. In there, we are assigning fab with the other Icon, based on the value of a fabIconNumber variable. We are are using fabIconNumber for storing the state of floatingActionButton, something like which Icon it is currently displaying.

You can write your own login and switch between as many number of Icons as required. Just wrap the logic around setState(){} in onPressed() of floatingActionButton.

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Icon fab = Icon(
    Icons.refresh,
  );

  int fabIconNumber = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("Flutter Tutorial - googleflutter.com"),
      ),
      floatingActionButton: FloatingActionButton(
        child: fab,
        onPressed: () => setState(() {
          if (fabIconNumber == 0) {
            fab = Icon(
              Icons.stop,
            );
            fabIconNumber = 1;
          } else {
            fab = Icon(Icons.refresh);
            fabIconNumber = 0;
          }
        }),
      ),
    );
  }
}

Screenshot

Change icon of Flutter FloatingActionButton when onPressed() action triggers

When on click on the FloatingActionButton with Refresh Icon, the icon is changed to Stop. Then again, if you click on the Stop icon, Refresh Icon appears in the FloatingActionButton.

Summary

In this Flutter Tutorial, we learned how to switch between or change the icon displayed in FloatingActionButton, with the help of well detailed Flutter Application.

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.