Closing ModalBottomSeet before time on Flutter causes black screen

I'm trying to create a modal bottom sheet using showModalBottomSheet, which wil display a form to register a todo item. The idea is that once the todo item is registered, I want to display a check icon from some seconds and then automatically close the sheet.

here is the snippet:

FloatingActionButton _floatingActionButton(BuildContext context) {
    return FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () async {
        await _showBottomSheet(
          context: context,
          content: CreateTodoForm(
            onClose: () {
              ...
              Navigator.pop(context);
            },
          ),
        );
      },
    );
  }

and inside the CreateTodoForm widget:

class _CreateTodoFormState extends State<CreateTodoForm> {
  TextEditingController titleController = TextEditingController();
  bool completed = false;
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => getIt<TodoFormBloc>(),
      child: BlocBuilder<TodoFormBloc, ITodoFormState>(
        builder: (context, state) {
          ...

          if (state is SubmittedTodo) {

            Future.delayed(Duration(seconds: 2), widget.onClose);

            return Container(
              height: 127,
              child: Icon(Icons.check, size: 50, color: Colors.white),
            );
          }

          ...
        },
      ),
    );
  }

Has you can see, when the state is SubmittedTodo (todo was submitted successfully) I return a container with the check icon, and after 2 seconds I call the onClose Function which is a call to Navigator.pop(context) to close the sheet.

This works great but it has a problem... if the user taps the < button on the device, or swipe the sheet down to dismiss it, before the 2 seconds are completed, then the sheet closes due to the user action, and then the future completes and it basically closes the app (the app get full black screen).

So my quiestion is how can I close the sheet automatically after some time safely without worring about what the user does.

enter image description here

1 answer

  • answered 2020-10-29 22:22 ikerfah

    Probably this is happening because of Navigator.pop(context); getting called after you click the back button which cause two pop. and the black screen is shown because there is no other screen to navigate back to.
    As a solution i propose wrapping your form widget by WillPopScope and then you will get notified that the user clicked on the back button. here you can close your form by calling onClose