首页 > 其他分享> > flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not co
flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not co
作者:互联网
代码如下:
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); })); }, ), ); } }
标签:thrown,exception,title,SnackBar,Scaffold,context,Text,new 来源: https://www.cnblogs.com/mingfeng002/p/11592228.html