flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold
代码如下:
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Returning Data', home: HomePage(), )); } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter SnackBar'), ), body: Center( child: MaterialButton( color: Colors.blue, child: new Text('点我'), onPressed: () { final snackBar = new SnackBar(content: new Text('这是一个SnackBar')); Scaffold.of(context).showSnackBar(snackBar); }, ), ), ); } }
当BuildContext在Scaffold之前时,调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决,代码如下:
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Returning Data', home: HomePage(), )); } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter SnackBar'), ), body: Builder( builder: (BuildContext context) { return new Center( child: MaterialButton( color: Colors.blue, child: new Text('点我'), onPressed: () { final snackBar = new SnackBar(content: new Text('这是一个SnackBar')); Scaffold.of(context).showSnackBar(snackBar); })); }, ), ); } }