Home > Back-end >  Flutter setState screen each time a global variable changes
Flutter setState screen each time a global variable changes

Time:01-03

I have a global variable and I want to setState the current screen each time its value changes.

Is that possible?

CodePudding user response:

you should use provider for that link,

  1. You start your root Build method in the app with:
@override
  Widget build(BuildContext context) {
    return MultiProvider(  // Multi means you can have more providers if you need
      providers: [
        ChangeNotifierProvider(builder: (context) => MyStateClass()),
      ],
      child: MaterialApp(....
  1. Now you can place all the data you need to share in the MyStateClass() and place underlying Widgets inside:
 Consumer<MyStateClass>(builder: (context, state, child) {

      // your code here - return(SomeOtherWidget());
    })
  1. or inside your Build methods:
  @override
  Widget build(BuildContext context) {
   MyStateClass state = Provider.of<MyStateClass>(context);
   // ... TODO  ... return (Widget)
  • Related