Home > Enterprise >  How to change theme to dark on click on IconButton?
How to change theme to dark on click on IconButton?

Time:05-17

In my application, in the appBar, there is a button that should change the theme to dark. I need to create functionality Provider. How can this be implemented? I just need to change the Scaffold color to black and the text color to white. My main.dart:

Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: const TextTheme(
          headline1: TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
          headline5: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
          subtitle2: TextStyle(fontSize: 10.0, color: Colors.black),
          bodyText1: TextStyle(fontSize: 14.0, color: Colors.black),
        ),
      ),
      home: const HomeScreen(),
    );
  }

My switch button:

appBar: AppBar(
        title: const Text('Flutter theme config'),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {

            },
            icon: const Icon(Icons.dark_mode),
          )
        ],
      ),

Theme provider:

class ThemeProvider extends ChangeNotifier {

}

CodePudding user response:

You can try something like this :

First we provide our Provider globally for the whole application, and then in the attribute theme: we listen for the change.

** main **

void main() async {
  runApp(
    MultiProvider( // create the provider
      providers: [
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(),
        )
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Material App',
      initialRoute: HomeScreen.routerName,
      routes: {
      },
      theme: Provider.of<ThemeProvider>(context).currentTheme, // listen to the current theme
    );
  }
}

In the provider we will only have two functions, one to switch to LightMode and the other to DarkMode, then we add it to the currentTheme variable which is the one that listens in the main

** ThemeProvider **

class ThemeProvider extends ChangeNotifier {
  ThemeData? currentTheme;

  setLightMode() {
    currentTheme = ThemeData(
      brightness: Brightness.light, // LightMode
      scaffoldBackgroundColor: Colors.red,
      [...] // more attributes
    );
    notifyListeners();
  }

  setDarkmode() {
    currentTheme = ThemeData(
      brightness: Brightness.dark, // DarkMode
      scaffoldBackgroundColor: Colors.green,
      [...] // more attributes
    );
    notifyListeners();
  }
}

Finally we create a StatefulWidget to change the isDarkMode variable to call the provider

** Button Home **

class _HomeScreenState extends State<SettingsScreen> {
  bool isDarkmode = false; // new variable

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Settings"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: IconButton(
             onPressed: () {
               final themeProvider =
                        Provider.of<ThemeProvider>(context, listen: false); // get the provider, listen false is necessary cause is in a function

               setState(() {
                  isDarkmode = !isDarkmode;
               }); // change the variable

               isDarkmode // call the functions
                  ? themeProvider.setDarkmode()
                  : themeProvider.setLightMode();
             },
             icon: const Icon(Icons.dark_mode),
          ),
        ),
    );
  }
}
  • Related