How to set state from another widget?

前端 未结 2 1388
一个人的身影
一个人的身影 2020-12-02 11:25

I\'m trying to change the state from a different widget in Flutter. For example, in the following example I set the state after a few seconds.

Here is the code for

2条回答
  •  -上瘾入骨i
    2020-12-02 11:54

    Avoid this whenever possible. It makes these widgets depends on each others and can make things harder to maintain in the long term.

    What you can do instead, is having both widgets share a common Listenable or something similar such as a Stream. Then widgets interact with each other by submitting events.

    For easier writing, you can also combine Listenable/Stream with respectively ValueListenableBuilder and StreamBuilder which both do the listening/update part for you.

    A quick example with Listenable.

    class MyHomePage extends StatelessWidget {
      final number = new ValueNotifier(0);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ValueListenableBuilder(
            valueListenable: number,
            builder: (context, value, child) {
              return Center(
                child: RaisedButton(
                  onPressed: () {
                    number.value++;
                  },
                  child: MyWidget(number),
                ),
              );
            },
          ),
        );
      }
    }
    
    class MyWidget extends StatelessWidget {
      final ValueListenable number;
    
      MyWidget(this.number);
    
      @override
      Widget build(BuildContext context) {
        return new Text(number.value.toString());
      }
    }
    

    Notice here how we have our UI automatically updating when doing number.value++ without ever having to call setState.

提交回复
热议问题