Reputation: 33
I want to change the theme to dark theme & return to light theme with this button:
IconButton(
icon: Icon(
Icons.brightness,
),
onPressed: () {
setState(() {
// Change to dark theme?
} else {
//Change it back to default light theme //How?
}
}
);
Main.dart
MaterialApp(
theme: ThemeData(
),
darkTheme: ThemeData(
brightness: Brightness.dark,
),
Upvotes: 3
Views: 912
Reputation: 5973
first is set to condition in your material theme (may be you define this is in main class)
import 'dart:async';
import 'package:flutter/material.dart';
StreamController<bool> setTheme = StreamController();
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder<bool>(
initialData: true,
stream: setTheme.stream,
builder: (context, snapshot) {
return MaterialApp(
theme: snapshot.data ? ThemeData.light() : ThemeData.dark(),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: Text("Your Theme")),
body: YourButtonPage()));/*Change this name with Your class*/
});
}
}
class YourButtonPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(
Icons.brightness_low,
size: 21,
),
alignment: Alignment.center,
onPressed: () {
setTheme.add(true);
}),
IconButton(
icon: Icon(
Icons.brightness_1,
size: 21,
),
alignment: Alignment.center,
onPressed: () {
setTheme.add(false);
}),
])));
}
}
Upvotes: 1
Reputation: 1476
You can use themeMode
property to choose which theme to use. It has three possible values:
Now the question is how to change it on button click?
Bad Method
Keep the value of themeMode
in a variable and use that variable instead of directly setting the themeMode
. On clicking of button change the state like:
setState((){
themeModeVariable = ThemeMode.dark;
});
Why this is bad? Let's say your button is located somewhere else and not where MaterialApp is located. The deeper you go, more problem you will face.
Good Method
Well the concept still is same but you use a state management solution to handle that problem. You can use Provider or BLoC or ReactiveX or Stacked or anything else.
I highly recommend you to learn a state management solution first. Check the official docs in flutter website
Upvotes: 0