Flutter:Scaffold.of() called with a context that does not contain a Scaffold.
程序员文章站
2022-06-12 22:51:29
...
Flutter:Scaffold.of() called with a context that does not contain a Scaffold.
当我第一次点击按钮想要弹出底部消息时出现了如下错误
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('SnackBar'),
leading: IconButton(
icon: Icon(Icons.chevron_left),
onPressed: () {
Navigator.pop(context);
},
),
),
body: Container(
alignment: Alignment.center,
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('测试'),
),
);
},
)
],
),
),
);
}
当BuildContext在Scaffold之前时,调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决,代码如下:
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('SnackBar'),
leading: IconButton(
icon: Icon(Icons.chevron_left),
onPressed: () {
Navigator.pop(context);
},
),
),
body: Container(
alignment: Alignment.center,
child: Column(
children: <Widget>[
Builder(
builder: (BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('测试'),
),
);
},
),
);
},
)
],
),
),
);
}