1

I want to showDialog when a page pushed. So I showDialog in it's initState:

class _Page2State extends State<_Page2> {
  @override
  void initState() {
    super.initState();
    _showDialog(context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(color: Colors.red),
    );
  }
}

void _showDialog({required BuildContext context}) {
  showCupertinoModalPopup(
    context: context,
    builder: (context) {
      return Container(
        width: 300,
        height: 100,
        color: Colors.green,
      );
    },
  );
}

No surprise, error showed:

dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>() or dependOnInheritedElement() was called before _Page2State.initState() completed.

To solve it, I changed code:

@override
void initState() {
  super.initState();
  WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
    _showDialog(context: context);
  });
}

It works. But I wonder is there any more elegant way?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
无夜之星辰
  • 5,426
  • 4
  • 25
  • 48

1 Answers1

2

Update: use WidgetsBinding.instance.addPostFrameCallback

Old: While using WidgetsBinding.instance?.addPostFrameCallback, you are showing dialog after finishing the init.

addPostFrameCallback: Schedule a callback for the end of this frame.

You can check previous question

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56