3

Please look at my code:

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
  }

}

So I have navigation drawer. One item ("Select city") does not close navigation drawer, it shows select city dialog:

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));
    });
  }

So, basically it's intended to show busy form, load cities, then hide busy form and show cities list dialog. As it seems to work, I'm getting exception:

I/flutter (10662): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter (10662): The following assertion was thrown while finalizing the widget tree: I/flutter (10662): setState() or markNeedsBuild() called when widget tree was locked. I/flutter (10662): This _ModalScope widget cannot be marked as needing to build because the framework is I/flutter (10662): locked. I/flutter (10662): The widget on which setState() or markNeedsBuild() was called was: I/flutter (10662):
_ModalScope-[LabeledGlobalKey<_ModalScopeState>#1f222](state: I/flutter (10662): _ModalScopeState#6c40b)

How to do what I want correctly?

user1209216
  • 7,404
  • 12
  • 60
  • 123
  • how exactly are you closing your drawer ? – Mazin Ibrahim Mar 07 '19 at 08:27
  • 3
    I noticed problem can be solved if I close drawer before attempting to change state. If drawer is still open and I want to change state, I'm getting this exception. – user1209216 Mar 07 '19 at 12:15
  • this kind of exception is noticed in the debugger only, but when you run this app on an actual device it won't have any noticeable effects.I tried that. – Mazin Ibrahim Mar 07 '19 at 12:19
  • Maybe related: https://stackoverflow.com/questions/45409565/flutter-setstate-or-markneedsbuild-called-when-widget-tree-was-locked – ch271828n Jul 10 '20 at 03:47

1 Answers1

0

This error means you are calling setState during the build phase, which you cannot do.

Hussein Abdallah
  • 1,452
  • 11
  • 13