Show dialog when the page finish init

Issue

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?

Solution

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

Answered By – Yeasin Sheikh

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *