flutter - 当在 FutureBuilder 中使用 Get.toNamed() 时,在构建期间调用 setState() 或 markNeedsBuild()
问题描述
使用flutter 2.x
和Get 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() 在构建期间引发了以下断言。
- 我试图检查
connectionStatus
(基于 SO 答案),但没有奏效。
有什么帮助吗?
解决方案
build
方法用于渲染 UI。您的逻辑根本与渲染无关,因此即使没有错误,将其放入build
方法中也没有意义。
最好将此方法转换为StatefulWidget
并将逻辑放入initState
,例如:
Future.delayed(const Duration(seconds: 4))
.then((value) => "done")
.then((_) => Get.toNamed("/login"));
推荐阅读
- android - 从 URI 获取图像路径时出现空指针异常错误
- python - 如何在单独的进程中运行 Python 自定义对象,所有这些都在共享事件队列上工作?
- java - 使用 mysql 驱动程序使用 mysql 数据库设置 spring-boot 项目
- angularjs - 在 Ionic3 中使用 InAppbrowser 打开浏览器时如何禁用后退按钮
- javascript - 使用比较表。添加多个表格时的移动响应问题?
- java - 为什么 nextLine() 在我的 Java 程序中不一直等待输入?
- emacs - 如何在我的程序中清除 Emacs 回显区域?
- ansible - 从 Ansible 中的地图列表中提取属性列表的正确方法
- codeblocks - 为什么我的 MSYS2/MinGW64 设置链接没有 -l 指令的 SDL2,而不是 SDL2_ttf?
- npm - 为什么`npm install` 在版本号中添加/删除插入符号(^)?