Warm tip: This article is reproduced from serverfault.com, please click

No Scaffold widget found : Getting exception while opening Bottom Dialog sheet

发布于 2020-02-05 08:36:49

I'm using Scaffold widget but while opening a bottom dialog sheet I'm getting this exception

@override
Widget build(BuildContext context) {

return Scaffold(
  appBar: AppBar(
    title: Text("Calendar"),
  ),
  body: SafeArea(
  .......
  .......

    child: GestureDetector(
                        onTap: (){
                          //getting exception here
                          showBottomSheet(
                              context: context,
                              builder: (context) => Container(
                                color: Colors.red,
                              ));
                        },

I'm stuck on this code, it'll be very helpful if someone can give any suggestion. Thank you.

Questioner
Ankit Dubey
Viewed
11
Pedro Massango 2020-09-14 23:42:58

The problem is that the context used to show the BottomSheet is not the context of the Scaffold. You can solve this issue by using GlobalKey or wrap your GestureDetector in a Builder widget so that it gives you the context that contains a reference of the Scaffold.

Here is a example using GlobalKey with the state of the Scaffold:

// created the ScaffoldState key    
final scaffoldState = GlobalKey<ScaffoldState>();
    
    class MyWidget extends StatelessWidget {
      void _showSheet() {
        // Show BottomSheet here using the Scaffold state instead ot«f the Scaffold context
        scaffoldState.currentState
            .showBottomSheet((context) => Container(color: Colors.red));
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            key: scaffoldState,
            appBar: AppBar(
              title: Text("Calendar"),
            ),
            body: SafeArea(child: GestureDetector(onTap: () {
              //getting exception here
              _showSheet();
            })));
      }
    }