showModalBottomSheet Function onClose

Issue

I want to add a function when the showModalBottomSheet is close or when the barrier tapped the function run(routing to the main page) but how?

I want to run this when the barrier tapped/modal closed

Navigator.pushNamedAndRemoveUntil(context, '/mainMenuPage', (route) => false);

Modal Code

showModalBottomSheet(
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(
        top: Radius.circular(25.0),
      ),
    ),
    backgroundColor: Colors.white,
    context: context,
    builder: (context) => Widget(...),
   );
  }

Solution

Try below code hope its help to you.

Your Widget with bottomSheet:

Center(
      child: ElevatedButton(
        child: const Text('showModalBottomSheet'),
        onPressed: () {
          showModalBottomSheet<void>(
            context: context,
            builder: (BuildContext context) {
              return Container(
                height: 200,
                color: Colors.amber,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      const Text('Modal BottomSheet'),
                    ],
                  ), //MyWidget()
                ),
              );
            },
          ).then(
            (value) => Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => MyWidget(),
              ),
            ),
          );
        },
      ),
    ),

Other class:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: Text(
          'Hello, World!',
          style: Theme.of(context).textTheme.headline4,
        ),
      ),
    );
  }
}

.then() -> This means that the next instructions will be executed. But it allows you to execute the code when the asynchronous method completes.

Answered By – Ravindra S. Patil

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.