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(),
),
],
),
),
);
}
}
>Solution :
The CupertinoSwitch is taking the value of isDarkMode, which is a getter that checks if _themeData is equal to darkMode. But in the themeData setter, you’re doing themeData = themeData, and both themeData here refer to the parameter (which shadows the themeData property of the class). Calling the actual themeData setter would be wrong too, because it will keep call itself indefinitely. What you have to do is to set _themeData instead.
set themeData(ThemeData themeData) {
_themeData = themeData;
notifyListeners();
}