0

i try to create a snackbar on scaffold, but error was Scaffold.of() called with a context that does not contain a Scaffold. and i can't solve it,i try to put a key but there is an error on it and can't setup an key, this is my code:



class Login extends StatelessWidget {

  
  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0.0,
          title: Text('Log in',
              style: TextStyle(color: Colors.black),
              textAlign: TextAlign.center),
        ),
        
                    SizedBox(
                        width: 500,
                        height: 50.0,
                        child: RaisedButton(
                            textColor: Colors.white,
                            color: Colors.blue,
                            child: Text('Log In'),
                            onPressed: () => {
                             Scaffold.of(context).showSnackBar(SnackBar(content: Text('Done!'),))
                            }))
                  ])
                ],
              ),
            ),
          ),
        ));
  }
}
AhdOthman
  • 47
  • 4
  • 1
    Does this answer your question ? https://stackoverflow.com/questions/51304568/scaffold-of-called-with-a-context-that-does-not-contain-a-scaffold/51304732 – void Aug 11 '20 at 17:02

1 Answers1

2

This problem can be fixed by adding a widget around the RaisedButton called Builder. This causes there to be a new context which fixes the problem because you are using the context of the widget that instantiated Scaffold not the context of a child of Scaffold. Hopefully this helps, I have included an updated code segment below to help!

class Login extends StatelessWidget {

  
  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0.0,
          title: Text('Log in',
              style: TextStyle(color: Colors.black),
              textAlign: TextAlign.center),
        ),
        
                    SizedBox(
                        width: 500,
                        height: 50.0,
                        child: Builder(
                           builder: (context) {
                             return RaisedButton(
                               textColor: Colors.white,
                               color: Colors.blue,
                               child: Text('Log In'),
                               onPressed: () => {
                                Scaffold.of(context).showSnackBar(SnackBar(content: Text('Done!'),))
                                })
                             }
                        )
                   )
                  ])
                ],
              ),
            ),
          ),
        ));
  }
}
Dbono.dev
  • 146
  • 5