I’ve this Flutter code with Two Widget. A widget with a MaterialApp and one ThemeData that call a stateless widget with one button.
I want to have more than one ThemeData and change between them with the button.
Is possible?
Thanks
import 'package:flutter/material.dart';
void main() {
runApp(const MyWidget());
}
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
fontFamily: 'Roboto',
appBarTheme: AppBarTheme(
color: Colors.green
),
primaryColor: Colors.deepOrangeAccent,
textTheme: const TextTheme(
displayLarge:
TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
titleLarge: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyMedium: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My Custom Theme App'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
},
child: const Text('Theme Button'),
),
),
);
}
}
2
Answers
Solution 1 :
Yes, it is possible to have multiple
ThemeData
instances and change between them using abutton
in your Flutter application. You will need to use Provider state management for that.reference :
How to Create Multiple Themes in Flutter Application?
Solution 2 (Optional) :
If you want to switch between
light mode
anddark mode
, you can follow this example:Here is a small example of how you can create and use multiple themes, using the provider package.
You can save the selected theme and perform read operations later using the shared_preferences package. To do this, you need to follow a slightly different approach.