Flutter update Widgets automatically based on parameter changes

1.1k views Asked by At

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?

1

There are 1 answers

0
Ruchit On BEST ANSWER

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)