Flutter: change dark mode switch to an Icon

Viewed 3473

I have implemented dark mode for my flutter project which is switched on/off using Swich placed in the Drawer, as you can see the following code:

final themeChange = Provider.of<DarkThemeProvider>(context);

ListTile(
              leading: Icon(Icons.brightness_2, size: 30.0, color: Colors.blue),
              title: Text('night mode', style: TextStyle(fontSize: 18.0)),
              trailing: Switch(
                value: themeChange.darkTheme,
                onChanged: (bool value) {
                  themeChange.darkTheme = value;
                },
              ),
            ),

This is the class

import 'package:flutter/foundation.dart';
import 'package:azkar/core/shared/sharedpreferances.dart';

class DarkThemeProvider with ChangeNotifier {
  DarkThemePreference darkThemePreference = DarkThemePreference();
  bool _darkTheme = false;

  bool get darkTheme => _darkTheme;

  set darkTheme(bool value) {
    _darkTheme = value;
    darkThemePreference.setDarkTheme(value);
    notifyListeners();
  }
}

The situation I am facing now is that some of the screens dose not have Drawer. Therefore, I wanted to be able to on/off the dark mode from the app bar of these screens, as you know putting switch in the app bar does not look good. How can I put an icon to do that, where the icon will change to another icon when it is on and back to the org. icon when change to off.

1 Answers

I managed to get the answer as follows:

First add this variable:

  var _icon = Icons.wb_sunny;

Then implement this code to change the icon and also switch the function between the dark mode and the light mode:

IconButton(
            icon: Icon(
              _icon,
              color: Colors.white,
              size: 30,
            ),
            onPressed: () {
              setState(() {
                if (_icon == Icons.wb_sunny) {
                  _icon = Icons.brightness_2;
                  themeChange.darkTheme = true;
                } else {
                  _icon = Icons.wb_sunny;
                  themeChange.darkTheme = false;
                }
              });
            },
          ),
Related