如你所见,我的按钮在刑台的身体里。但是我得到了这个异常:
使用不包含脚手架的上下文调用Scaffold.of()。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SnackBar Playground'),
),
body: Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: _displaySnackBar(context),
child: Text('Display SnackBar'),
),
),
);
}
}
_displaySnackBar(BuildContext context) {
final snackBar = SnackBar(content: Text('Are you talkin\' to me?'));
Scaffold.of(context).showSnackBar(snackBar);
}
编辑:
我找到了这个问题的另一个解决方案。如果我们给Scaffold一个键GlobalKey<ScaffoldState>,我们就可以像下面那样显示SnackBar,而不需要在Builder小部件中包装我们的主体。返回脚手架的小部件应该是一个有状态的小部件。
_scaffoldKey.currentState.showSnackBar(snackbar);
Expanded(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Builder(
builder: (context) => RaisedButton(
onPressed: () {
final snackBar = SnackBar(
content: Text("added to cart"),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change.
},
),
);
},
textColor: Colors.white,
color: Colors.pinkAccent,
child: Text("Add To Cart",
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w600)),
),
),
),
)
更新- 2021年
脚手架.of(context)已弃用,改用ScaffoldMessenger。
从方法的文档中检查:
脚手架信使现在处理SnackBars以便持久跨
并且总是显示在当前脚手架上。缺省情况下,
脚手架信使的根是包含在MaterialApp,但你可以
为ScaffoldMessenger创建自己的可控范围
控制哪个脚手架接收你的零食棒。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Demo')
),
body: Builder(
// Create an inner BuildContext so that the onPressed methods
// can refer to the Scaffold with Scaffold.of().
builder: (BuildContext context) {
return Center(
child: RaisedButton(
child: Text('SHOW A SNACKBAR'),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Hello!'),
));
},
),
);
},
),
);
}
你可以在这里查看详细的弃用和新方法:
Expanded(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Builder(
builder: (context) => RaisedButton(
onPressed: () {
final snackBar = SnackBar(
content: Text("added to cart"),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change.
},
),
);
},
textColor: Colors.white,
color: Colors.pinkAccent,
child: Text("Add To Cart",
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w600)),
),
),
),
)