首页 > 解决方案 > 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)

如何正确地做我想做的事?

标签: exceptiondartflutterstate

解决方案


此错误意味着您在构建阶段调用 setState,这是您无法做到的。


推荐阅读