原因:当BuildContext在Scaffold之前时,调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决,代码如下:
var _scaffoldkey = new GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldkey,)
}
void showSnackBar(String message) {
var snackBar = SnackBar(content: Text(message));
_scaffoldkey.currentState.showSnackBar(snackBar);
}