Basically the title. I apply the functions to the CupertinoSwitch values but it doesn’t toggle. To make sure of it, if I hardcode the value to true, the switch turns green, so I guess it’s something in the onChanged. Am I toggling it wrong inside the theme_provider?
theme_provider.dart
import 'package:chat_app/themes/dark_mode.dart';
import 'package:chat_app/themes/light_mode.dart';
import 'package:flutter/material.dart';
class ThemeProvider extends ChangeNotifier {
final ThemeData _themeData = lightMode;
ThemeData get getTheme => _themeData;
bool get isDarkMode => _themeData == darkMode;
set themeData(ThemeData themeData) {
themeData = themeData;
notifyListeners();
}
void toggleTheme() {
themeData = isDarkMode ? lightMode : darkMode;
}
}
settings.dart
import 'package:chat_app/themes/theme_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.background,
appBar: AppBar(
title: const Text("Settings"),
backgroundColor: Colors.transparent,
elevation: 0,
foregroundColor: Colors.grey,
),
body: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondary,
borderRadius: BorderRadius.circular(12),
),
margin: const EdgeInsets.all(25),
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Dark Mode"),
CupertinoSwitch(
value: Provider.of<ThemeProvider>(context).isDarkMode,
onChanged: (value) =>
Provider.of<ThemeProvider>(context, listen: false)
.toggleTheme(),
),
],
),
),
);
}
}
2
Answers
Add notifyListeners() statement after this line :
themeData = isDarkMode ? lightMode : darkMode;
and make sure that you added a ThemeProvider object in a changenotifierprovider wrapped around the materialapp
The
CupertinoSwitch
is taking the value ofisDarkMode
, which is a getter that checks if_themeData
is equal todarkMode
. But in thethemeData
setter, you’re doingthemeData = themeData
, and boththemeData
here refer to the parameter (which shadows thethemeData
property of the class). Calling the actualthemeData
setter would be wrong too, because it will keep call itself indefinitely. What you have to do is to set_themeData
instead.