首页 > 解决方案 > 当在 FutureBuilder 中使用 Get.toNamed() 时,在构建期间调用 setState() 或 markNeedsBuild()

问题描述

使用flutter 2.xGet package版本^4.1.2

我有一个像这样的小部件:

class InitializationScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future:
            // this is just for testing purposes
            Future.delayed(const Duration(seconds: 4)).then((value) => "done"),
        builder: (context, snapshot) {
          if (shouldProceed(snapshot)) {
            Get.toNamed("/login");
          }

          if (snapshot.hasError) {
            // handle error case ...
          }

          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }

  bool shouldProceed(AsyncSnapshot snapshot) =>
      snapshot.hasData && snapshot.connectionState == ConnectionState.done;
}

Get.toNamed("/login");在内部使用FutureBuilder会导致此错误:

构建 FutureBuilder(dirty, state: _FutureBuilderState#b510d): setState() 或 markNeedsBuild() 在构建期间引发了以下断言。

有什么帮助吗?

标签: flutterflutter-getx

解决方案


build方法用于渲染 UI。您的逻辑根本与渲染无关,因此即使没有错误,将其放入build方法中也没有意义。

最好将此方法转换为StatefulWidget并将逻辑放入initState,例如:

Future.delayed(const Duration(seconds: 4))
  .then((value) => "done")
  .then((_) => Get.toNamed("/login"));

推荐阅读