Switching Themes Using FAB

In this lesson, you'll learn how to use a floating action button (FAB for short) to toggle between dark theme to light theme and vice versa.

Switching themes using FAB

A floating action button (FAB) represents the primary action on the screen. Let’s add a FAB to toggle between dark and light themes.

Theme types using enum

We’ll use an enum to hold the available themes. Enumeration or enum is used for defining named constant values. We’re using enum APP_THEME to name available themes.

enum APP_THEME { LIGHT, DARK }

The currentTheme variable is used to keep track of the currently selected theme.

  var currentTheme = APP_THEME.LIGHT;

FAB to toggle between themes

We’ll add a FAB to be able to trigger theme switching.

Since we added a new FloatingActionButton widget to our interface, we would also need to provide an appropriate theme for the light and dark app’s brightness.

FAB dark theme

The floatingActionButtonTheme property is used to provide a theme for the FAB widget. In the dark theme, the background is preferred to be dark, while the foreground is light.

  static ThemeData appThemeDark() {
    return ThemeData(
      ...

      floatingActionButtonTheme: FloatingActionButtonThemeData(
        //dark background for FAB
        backgroundColor: Colors.black,

        //White plus (+) sign for FAB  
        foregroundColor: Colors.white,
      ),
    );
  }

FAB light theme

In the light theme, the light background is preferred, while the foreground is dark.

  static ThemeData appThemeLight() {
    return ThemeData(
      ...

      floatingActionButtonTheme: FloatingActionButtonThemeData(
        //White background
        backgroundColor: Colors.white,
        
        //Black plus (+) sign for FAB  
        foregroundColor: Colors.black,
      ),
    );
  }

Switching theme

If a dark theme is selected, then switch to light themes and vice versa.

currentTheme == APP_THEME.DARK
   ? currentTheme = APP_THEME.LIGHT
   : currentTheme = APP_THEME.DARK;

Accessing currentTheme

If the currentTheme is APP_THEME.DARK, then apply a dark theme or vice versa.

MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: currentTheme == APP_THEME.DARK
          ? MyAppThemes.appThemeDark()
          : MyAppThemes.appThemeLight(),
      home: Scaffold(
        appBar: buildAppBarWidget(),
        body: buildBodyWidget(),
        floatingActionButton: FloatingActionButton(
          child: IconButton(
            icon: Icon(Icons.threesixty),
            onPressed: () {
              setState(() {
                currentTheme == APP_THEME.DARK
                    ? currentTheme = APP_THEME.LIGHT
                    : currentTheme = APP_THEME.DARK;
              });
            },
          ),
        ),
      )

Get hands-on with 1400+ tech skills courses.