How to Solve 'No Scaffold widget found' error in Flutter when using showBottomSheet

How to Solve ‘No Scaffold widget found’ error in Flutter when using showBottomSheet

When you try to use showBottomSheet in a Flutter application, then you may come across the error message ‘No Scaffold widget found’ with an additional info such as

WidgetName widgets require a Scaffold widget ancestor.

The specific widget that could not find a Scaffold ancestor was: WidgetName

Example code that gives the error can be like this

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(onPressed: () {
                showBottomSheet(
                    context: context,
                    builder: (BuildContext context) {
                      return Container(
                        color: Colors.blue,
                        child: Column(
                          children: [
                            Text('Bottom Sheet')
                          ],
                        ),
                      );
                    } );
              } , child: Text('Show Bottom Sheet'))
            ],
          ),
        ),
      ),
    ) ;
  }

The reason for getting this error is, the showBottomSheet requires the context of a Scaffold widget. The context we passed to this is not the context of the Scaffold widget but of the entire Widget itself.

Solution for ‘No Scaffold widget found’ error in Flutter when using showBottomSheet

Solution 1:

If you are not very specific about the type of widget that you are using, then instead of showBottomSheet , you can use showModalBottomSheet.

Solution 2:

If you want to use only showBottomSheet, then as the error says, we need to pass the context of the Scaffold widget to this function. To do this, we can generate a global key for Scaffold widget and run the showBottomSheet function on its context.

example:

final scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(),
      body: Container(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(onPressed: () {
                scaffoldKey.currentState!.
                showBottomSheet((context) {
                  return Container(
                    color: Colors.blue,
                    child: Column(
                      children: [
                        Text('Bottom Sheet')
                      ],
                    ),
                  );
                });
              } , child: Text('Show Bottom Sheet'))
            ],
          ),
        ),
      ),
    ) ;
  }

Leave A Comment

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