exception - setState() 或 markNeedsBuild() 在小部件树被锁定时调用 >。改变状态时
问题描述
请看我的代码:
class HomePageState extends State<HomePage> {
bool _isLoading = false;
.....
@override
Widget build(BuildContext context) {
var drawerOptions = <Widget>[];
......
drawerOptions.add(new ListTile(
leading: new Icon(Icons.account_balance),
title: new Text(Strings.menu_change_city),
onTap: () => createDialog()
));
if(_isLoading) return buildBusyForm();
return Scaffold( .... //window content
}
}
所以我有导航抽屉。一项(“选择城市”)不关闭导航抽屉,它显示选择城市对话框:
createDialog() {
setState(() {_isLoading = true;});
fetchCities().then((response) {
setState(() {_isLoading = false;});
showDialog(
context: context,
builder: (context) => CityChoiceDialog<City>(
title: Text(Strings.menu_change_city),
items: response,
initialValue: response.firstWhere((c) => c.id == globals.cityId, orElse: () => new City()),
itemBuilder: (City city) => Text(city.name),
onSelected: _onSelected,
onSubmitted: _onSubmitted));
});
}
所以,基本上它的目的是显示繁忙的表格,加载城市,然后隐藏繁忙的表格并显示城市列表对话框。因为它似乎有效,我得到了例外:
I /颤振(10662):══╡小部件库发现异常╞═════════════════════════════════════════════ ═════════════════════════ I/flutter (10662):在最终确定小部件树时引发以下断言:I/flutter (10662): setState() 或 markNeedsBuild() 在小部件树被锁定时调用。I/flutter (10662): 这个 _ModalScope 小部件不能被标记为需要构建,因为框架是 I/flutter (10662): 锁定的。I/flutter (10662):调用 setState() 或 markNeedsBuild() 的小部件是:I/flutter (10662):
_ModalScope-[LabeledGlobalKey<_ModalScopeState>#1f222](state: I/flutter (10662): _ModalScopeState #6c40b)
如何正确地做我想做的事?
解决方案
此错误意味着您在构建阶段调用 setState,这是您无法做到的。
推荐阅读
- javascript - 此代码使用 %3-22 cpu 对 PhaserJS 是否有效?
- c# - 附加 DLL 后,Windows 程序无法在另一台计算机上运行
- powershell - Powershell 替换 Unicode 字符,如“çöşİğü”
- docker - 有没有办法设置多个本地 Go 模块,这样它们就可以在一个 Docker 容器中运行而无需从 Github 中提取?
- angular - 使用 ngx-translate 为每种语言使用多个 JSON 进行翻译
- discord.js - 如何制作邀请命令,根据成员是否仍在服务器中进行更新
- javascript - 数字总和,更清晰的 JS 版本
- c# - 如何以编程方式在 wpf 应用程序中添加元素
- performance - Imagemagick 转换超慢
- javascript - 如何在 Vue 中使用渲染函数使 DOM 反应?