问题描述
我尝试在脚手架上创建一个快餐栏,但错误是在不包含脚手架的上下文中调用了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!'),))
})
}
)
)
])
],));
}
}