Home > Software design >  Building overlay on top of screen
Building overlay on top of screen

Time:05-26

I have method to show progress indicator on the top of screen.

It works but when Navigator.of(context).pop(); is called main screen is black out , I want to remove only CircularProgressIndicator(), though

myShowDialog() async{
    ShowDialog(
      context: context,
      builder: (context) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
    try {
      await Future.delayed(const Duration(seconds: 5));
    } finally {
      Navigator.of(context).pop();
    }
}

And I call this from here.

onPressed: (){
      myShowDialog();
},

How can I use correctly this??

CodePudding user response:

Because you are using the context of the main screen to pop. So try to move the pop function like below.

myShowDialog() async{
    ShowDialog(
      context: context,
      builder: (context) {
        Future.delayed(const Duration(seconds: 5)).then((_) {
          Navigator.of(context).pop();
        });

        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
}

But, I recommend creating another dialog widget class. And call the Future.delayed function in the initState function. Because calling it in the builder has some potential risks.

class YourDialog extends StatefulWidget {
  const YourDialog({Key? key}) : super(key: key);

  @override
  State<YourDialog> createState() => _YourDialogState();
}

class _YourDialogState extends State<YourDialog> {

  @override
  void initState() {
    super.initState();
    Future.delayed(const Duration(seconds: 5)).then((_) {
      if (mounted) Navigator.of(context).pop();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: CircularProgressIndicator(),
    );
  }
}
  • Related