一个选项是在对话框中使用两个上下文,并使用传递给对话框的上下文来搜索Scaffold。
当你显示一个对话框时,你显示的是一个完全不同的页面/路由,它超出了调用页面的范围。所以没有脚手架。
下面是一个使用第一页范围的工作示例。
但是,问题在于 SnackBar 没有被删除。
如果您改为使用GlobalKey 来获取Scaffold,问题是一样的。
在这种情况下,我会考虑不使用 Snackbar,因为它与下面的页面相关联。它甚至被对话框阴影变灰。
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
_showDialog(BuildContext context1) {
return showDialog(
context: context1,
builder: (BuildContext context) {
return AlertDialog(
content: Text("Dialog"),
actions: <Widget>[
new FlatButton(
child: new Text("OK"),
onPressed: () => Scaffold.of(context1).showSnackBar(SnackBar(
content: Text("Pressed"),
)),
),
],
);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Test"),
actions: <Widget>[
PopupMenuButton(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry>[
PopupMenuItem(
child: ListTile(
title: Text('Show dialog'),
onTap: () => _showDialog(context),
),
),
];
},
)
],
),
);
}
}