I have used the provider for changing themes, this is the code for light and dark theme. The main purpose of my question is to change the theme with a switch, not with a button. The theme can be changed with a button correctly using "int mode". But when I use "bool mode" because of a switch. The switch needs a value of true or false.
How to implement this switch for changing the light and dark theme? I need a switch, not a button.
import 'package:flutter/material.dart';
class AppStyleModeNotifier extends ChangeNotifier {
bool mode = true; //0 for light and 1 for dark
Color primaryBackgroundColor = Colors.white;
Color appBarBackgroundColor = Colors.cyan[200];
Color boxColor = Colors.blue[50];
Color boxTextColor = Colors.indigo;
Color primaryTextColor = Colors.white;
Color dashboardColor = Colors.cyan;
Color dashboardTextColor = Colors.red[600];
Color dashboardIconColor = Colors.yellow[200];
//Color typeMessageBoxColor = Colors.grey[200];
switchMode() {
if (mode == true) {
//if it is light mode currently switch to dark
primaryBackgroundColor = Colors.grey[900];
appBarBackgroundColor = Colors.grey[800];
// boxColor = Colors.grey[600];
boxColor = Colors.black;
boxTextColor = Colors.grey[100];
primaryTextColor = Colors.black;
dashboardColor = Colors.grey[900];
dashboardTextColor = Colors.grey[400];
dashboardIconColor = Colors.white;
//typeMessageBoxColor = Colors.grey[800];
mode = false;
} else {
//if it is dark mode currently switch to light
primaryBackgroundColor = Colors.white;
appBarBackgroundColor = Colors.cyan[200];
boxColor = Colors.tealAccent;
boxTextColor = Colors.indigo;
primaryTextColor = Colors.white;
dashboardColor = Colors.cyan;
dashboardTextColor = Colors.red[600];
dashboardIconColor = Colors.yellow[200];
//typeMessageBoxColor = Colors.grey[200];
mode = true;
}
notifyListeners();
}
}
Following is the Switch for changing the light and dark theme. This Switch is not working correctly, Is there any mistake in the code. Instead of a switch using a button, it works fine.
import 'package:provider/provider.dart';
import '../FreelanceTheme/AppStyleModeNotifier.dart';
class HomePage extends StatelessWidget with NavigationStates {
const HomePage({Key key, this.onMenuTap}) : super(key: key);
@override
Widget build(BuildContext context) {
final appStyleMode = Provider.of<AppStyleModeNotifier>(context);
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xffE5E5E5),
appBar: AppBar(
elevation: 0,
backgroundColor: appStyleMode.appBarBackgroundColor,
actions: <Widget>[
Switch(
value: appStyleMode.mode,
onChanged: appStyleMode.switchMode(),
),
Change your code to this, it'll be work.
Switch(
value: appStyleMode.mode,
onChanged: (value)=> appStyleMode.switchMode(),
),