How to change the theme in flutter using darkTheme:
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.
Comments
-
avimimoun over 1 year
To manage themes in my MaterialApp(), i use :
MaterialApp( ... theme: isDarkTheme ? darkTheme() : lightTheme(), )
darkTheme()
andlightTheme()
are just simple function that returnThemeData()
So, I use an inherited Widget to change the variable
isDarkTheme
and then i use thesetState((){})
method and all the application is rebuildBut, 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