I'm trying to implement dark mode in my flutter app using provider, but I'm having some issues:
I have a home screen that it has a scaffold widget. The body of the scaffold is a Stack with two different classes, as you can see here:
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: Constant.menuOn
? BorderRadius.circular(60.0)
: BorderRadius.circular(0.0),
child: Scaffold(
body: Stack(
children: const [
Menu(),
HomeScreen(),
],
),
),
);
}
The home screen class has another Scaffold widget, where hos body has another class called body. It is from the body where I'm able to change the theme of my app using a switch where I can set state my BODY class with the provider as you can see here:
lsetState(() {
final provider = Provider.of<ThemeProvider>(
context,
listen: false);
rovider.toggleTheme(Constant.isDarkMode);
});
My body class change the theme however the class that is under the body class (Remember that my class "MENU" is under the class BODY because the first stake), does not change theme until restart my app (I'm using the same parameters of the body in order to know when has to change the class)...
I want to know how I can set the theme state of my menu class, or in general how I can change any other state from any class.
Note: Both of my class are StatefulWidget.
CodePudding user response:
In general, setState
is a very local intra-widget operation. Local data has changed, so the local view needs updating. Wanting to call the setState of another widget is a bad code smell. If you need other views depending on data you've updated, consider one of the state management solutions. (I would, for example, use a Riverpod Provider to hold the data, then watch that in every dependent view.)