-2

I have a global variable and I want to refresh my Widgets automatically (without using setState each time) whenever its value changes.

Is that possible?

genericUser
  • 4,417
  • 1
  • 28
  • 73

1 Answers1

1

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)
Ruchit
  • 2,137
  • 1
  • 9
  • 24