Creating a dynamic theme for your Flutter app allows your users to change the color scheme of your app at runtime. This can be achieved by using the Provider package, which is a popular state management library for Flutter.
Here's an example of how you can implement a dynamic theme in your Flutter app using Provider:
Add the Provider package to your pubspec.yaml file:
provider: ^4.3.2+1
Create a new dart file, for example, theme_provider.dart, to define your theme data.
class ThemeProvider with ChangeNotifier {
ThemeData _themeData;
ThemeProvider(this._themeData);
ThemeData get themeData => _themeData;
set themeData(ThemeData value) {
_themeData = value;
notifyListeners();
}
}
In main.dart file, create an instance of ThemeProvider and wrap your MaterialApp widget with a ChangeNotifierProvider:
void main() {
final themeProvider = ThemeProvider(ThemeData.light());
runApp(ChangeNotifierProvider(
create: (context) => themeProvider,
child: MyApp(),
));
}
Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
theme: themeProvider.themeData,
home: MyHomePage(),):},),
RaisedButton(
onPressed: () {
themeProvider.themeData = ThemeData.dark();
},
child: Text('Dark Mode'),
),
Comments
Post a Comment