Ashtav
Ashtav

Reputation: 2966

How to use showModalBottomSheet in StatelessWidget?

I try to code like this

showModalBottomSheet(
   context: context, // I got error here (Undefined name 'context'.dart(undefined_identifier))
   builder: (context){

   return Container(

   );
);

I got error on context: context, error message is

Undefined name 'context'.dart(undefined_identifier)

Upvotes: 1

Views: 1504

Answers (3)

CopsOnRoad
CopsOnRoad

Reputation: 267404

You are getting this error because you don't have access to context everywhere in a StatelessWidget class. All you need to do is pass context from build() if you are using this outside build() method else use it within build() method.


Solution 1. (Using inside build())

@override
Widget build(BuildContext context) {
  return RaisedButton(
    child: Text("Show sheet"),
    onPressed: () {
      showModalBottomSheet(context: context, builder: (context) => YourWidget());
    },
  );
}

Solution 2. (Using outside build())

@override
Widget build(BuildContext context) {
  return RaisedButton(
    child: Text("Show sheet"),
    onPressed: () => _showSheet(context),
  );
}

void _showSheet(BuildContext context) {
  showModalBottomSheet(context: context, builder: (context) => YourWidget());
}

Upvotes: 1

Sami Kanafani
Sami Kanafani

Reputation: 15741

This is how you call the showModalBottomSheet in a StatelessWidget

class TestStatelessWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return RaisedButton(
      child: Text('Press me'),
      onPressed: ()=>showPress(context),
    );
  }

  void showPress(BuildContext context){
    showModalBottomSheet(context:context, builder: (context){
      return Text('hello');
    });
  }



}

Upvotes: 5

Robin Reiter
Robin Reiter

Reputation: 2517

You did not close your showModalBottomSheet's builder correctly. There is a } missing.

This would be the correct usage:

showModalBottomSheet(
    context: context,
    builder: (builder){
      return Container();
    }
);

Upvotes: 0

Related Questions