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(),
));
}
In your widgets that need to access the theme data, you can use the Consumer widget.
Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
theme: themeProvider.themeData,
home: MyHomePage(),):},),
In the button to switch theme, you can call the setter method of the themeProvider
RaisedButton(
onPressed: () {
themeProvider.themeData = ThemeData.dark();
},
child: Text('Dark Mode'),
),
You can also create different themes and switch between them in a similar way.With this approach, your users can change the color scheme of your app at runtime and your widgets will automatically update to reflect the new theme.
Keep in mind that this is just an example, you can always customize it based on your needs and preferences.
Thankyou;
0 Comments