Wouter Vandenputte
Wouter Vandenputte

Reputation: 2113

Flutter: showing a dialog at startup

I'm quite familiair with Flutter by now but I can't wrap my head around this.

I want to show a dialog on the first launch in a State<T> class where T is a stateful widget. the dialog contains some short instructions about how to use the app. But doing this logic in the build method throws an error, as well as in the initState as in the didChangeDependencies method.

So where (or rather when) could I possibly call the following logic

if(someCondition)
   showDialog(...);

Without getting the following error

The following assertion was thrown building FutureBuilder(state: _FutureBuilderState#66844): setState() or markNeedsBuild() called during build.

This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: Overlay-[LabeledGlobalKey#27d99] state: OverlayState#4aeab(entries: [OverlayEntry#3c67c(opaque: true; maintainState: false), OverlayEntry#564f9(opaque: false; maintainState: true), OverlayEntry#7b46b(opaque: false; maintainState: false), OverlayEntry#81c9d(opaque: false; maintainState: true)]) The widget which was currently being built when the offending call was made was: FutureBuilder state: _FutureBuilderState#66844

Upvotes: 0

Views: 556

Answers (1)

dm_tr
dm_tr

Reputation: 4783

Ensure your widget is completely built before attempting to show a dialog

@override
void initState() {
  super.initState();

  WidgetsBinding.instance.addPostFrameCallback((_) {
    showDialog(
      // ...
    );
  });
}

Upvotes: 2

Related Questions