How to change the theme in flutter using darkTheme:

1,869

darkTheme property is used to define a Theme to be used when the device enters Dark mode, So you can't force your app to use darkTheme property because it depends on the value of MediaQueryData.platformBrightness which is a read-only field.

You can rather define several Themes to be used as a value for Theme property, and switching between them during the app course by using a StreamBuilder wrapped around your MaterialApp,which won't cause the app to stop and rebuild like the case when you were using setState to change theme (you'll need rxdart package to apply the below solution):

   //BehaviorSubject stream any changes immediately without explicit call
   var themeSubject = BehaviorSubject<ThemeData>();

   //This way the app won't rebuild when the user selects the same theme
   Stream<ThemeData> getTheme() => themeSubject.stream.distinct(); 

   void setTheme (MaterialColor color){
       pointsSubject.sink.add(ThemeData(primarySwatch: color) ;
   }


   return StreamBuilder<ThemeData>(
             stream: getTheme(),
             initialData: ThemeData(
                primarySwatch: Colors.blue,
                primaryTextTheme: TextTheme(
                  title: TextStyle(color: Colors.white),
                ),
             builder: (context, themeSnapshot){
                 return MaterialApp(theme: themeSnapshot.data);
             }
          ): 

Then use your InheritedWidget to access setTheme and change it as you please.

Share:
1,869
avimimoun
Author by

avimimoun

I'm a student full stack developer

Updated on December 13, 2022

Comments

  • avimimoun
    avimimoun over 1 year

    To manage themes in my MaterialApp(), i use :

    MaterialApp(
      ...
      theme: isDarkTheme ? darkTheme() : lightTheme(),
    )
    

    darkTheme() and lightTheme() are just simple function that return ThemeData()

    So, I use an inherited Widget to change the variable isDarkTheme and then i use the setState((){}) method and all the application is rebuild

    But, I saw on the Flutter documentation that we can use darkTheme:.

    I'm trying to do this :

    MaterialApp(
      ...
      theme: lightTheme(),
      darkTheme: darkTheme()
    )
    

    And we can change the theme during the course of the application