flutter - Flutter-SnackBar 未显示在 TabBarView 中
问题描述
这是来自 Flutter.io 的官方标签演示。我想在一个由 RadioButton 触发的选项卡中添加小吃栏。
我确实将它包装在一个 Scaffold 小部件中。它不在 TabBarView 中工作,而是在单个单选按钮中工作。但是当我将 Snackbar 放在选项卡中时,什么也没有显示。
代码的主要部分如下所示
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new DefaultTabController(
length: 3,
child: new Scaffold(
appBar: new AppBar(
bottom: new TabBar(tabs: [
new Tab(icon: new Icon(Icons.home)),
new Tab(icon: new Icon(Icons.favorite)),
new Tab(icon: new Icon(Icons.list))
]),
title: new Text("Tabs Demo"),
),
body: new TabBarView(children: [
new MyHomePage(),
new Center(
child: new RaisedButton(
onPressed: () {
final snackBar = new SnackBar(
content: new Text('Yay! A SnackBar!'),
action: new SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
},
child: new Text('Show SnackBar'),
)
),
new Center(
child: new IconButton(icon: new Icon(Icons.add), onPressed: (){
final snackBar = new SnackBar(
content: new Text('Yay! A SnackBar!'),
action: new SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
})
),
]),
)),
);
}
}
解决方案
Add a GlobalKey of the Scaffold state and use that to display SnackBar as below,
GlobalKey<ScaffoldState> scaffoldState = new GlobalKey();
Scaffold(
key: scaffoldState,
....
scaffoldState.currentState.showSnackBar(new SnackBar(content: new Text('Hello!')));
....
);