Scaffold.of() 使用不包含脚手架的上下文调用。问题

Scaffold.of() called with a context that does not contain a Scaffold. problem

我尝试在脚手架上创建小吃店,但错误是 Scaffold.of() 使用不包含脚手架的上下文调用。我无法解决它,我尝试输入一个密钥,但上面有一个错误,无法设置密钥,这是我的代码:



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!'),))
                            }))
                  ])
                ],
              ),
            ),
          ),
        ));
  }
}

这个问题可以通过在 RaisedButton 周围添加一个名为 Builder 的小部件来解决。这会导致出现一个新的上下文来解决问题,因为您使用的是实例化 Scaffold 的小部件的上下文,而不是 Scaffold 的子项的上下文。希望这有帮助,我在下面包含了更新的代码段以提供帮助!

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!'),))
                                })
                             }
                        )
                   )
                  ])
                ],
              ),
            ),
          ),
        ));
  }
}