如何从另一个小部件设置状态? [英] How to set state from another widget?

查看:100
本文介绍了如何从另一个小部件设置状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Flutter中的其他窗口小部件更改状态。例如,在以下示例中,我将在几秒钟后设置状态。

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.

以下是代码:

class _MyAppState extends State<MyApp> {

  int number = 1;

  @override
  void initState() {
    super.initState();
    new Future.delayed(new Duration(seconds: 5)).then((_) {
      this.setState(() => number = 2);
      print("Changed");
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new FlatButton(
          color: Colors.blue,
          child: new Text("Next Page"),
          onPressed: () {
            Navigator.of(context).push(new MaterialPageRoute(
              builder: (BuildContext context) => new StatefulBuilder(builder: (BuildContext context, setState) =>new MySecondPage(number))
            ));
          },
        ),
      ),
    );
  }
}

我尝试使用 InheritedWidget ,但是除非我将其包装在顶层小部件上,否则这将无法工作,这对我要执行的操作不可行(上面的代码是我要进行的操作的简化实现)。

I tried using an InheritedWidget, but that won't work unless I wrap it around my top level widget, which is not feasible for what I'm trying to do (the code above is a simplification of what I'm trying to achieve).

关于在Flutter中实现此目标的最佳方法的任何想法?

Any ideas on what the best way of achieving this is in Flutter?

推荐答案

尽可能避免这样做。这样会使这些小部件相互依赖,并且从长远来看会使它们变得更难维护。

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

您可以做的是,让两个小部件共享一个共同的 Listenable 或类似的东西例如 Stream 。然后,小部件通过提交事件进行交互。

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.

为了便于编写,您还可以组合 Listenable / Stream 分别与 ValueListenableBuilder StreamBuilder 都为您完成了侦听/更新部分。

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

带有 Listenable的快速示例

class MyHomePage extends StatelessWidget {
  final number = new ValueNotifier(0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ValueListenableBuilder<int>(
        valueListenable: number,
        builder: (context, value, child) {
          return Center(
            child: RaisedButton(
              onPressed: () {
                number.value++;
              },
              child: MyWidget(number),
            ),
          );
        },
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  final ValueListenable<int> number;

  MyWidget(this.number);

  @override
  Widget build(BuildContext context) {
    return new Text(number.value.toString());
  }
}

请注意,在执行操作时如何自动更新用户界面 number.value ++ 无需调用 setState

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

这篇关于如何从另一个小部件设置状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆