首页 > 解决方案 > Flutter 中的 OnStateChanged 方法

问题描述

在 Flutter 中,是否有类似onStateChanged的​​方法在页面状态发生变化时被调用?

setState(() {
  widget._loadCompleted = true;
  widget._loading = false;
});

我正在尝试在setState()方法中设置两个布尔值。我出于其他几个原因设置状态。所以我想知道最后一次状态变化是否是出于这个特殊原因。

标签: flutterstate

解决方案


正如 Günter 所说,没有像onStateChanged(). 你必须用build()方法处理它。

如果我说得对,你可以这样使用:

class _MyAppState extends State<MyApp> {
  bool myFlag = false; // initially set to false

  void _doYourWork() {
    setState(() => myFlag = true); // set to true here
  }

  @override
  Widget build(BuildContext context) {
    if (myFlag) {
      // setState() just got called
    } else {
       // we are building fresh for the first time. 
    }
    myFlag = false;
    return yourWidget();
  }
}

在此之后build()将收到myFlag值,true然后可以false再次设置为。所以,你可以做到这一点。


推荐阅读