有没有办法使用SnackBar
与CupertinoPageScaffold
?
我收到以下错误:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of().
使用以下命令在子窗口小部件中调用SnackBar
:
final snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
你需要包含一个Scaffold
,因为CupertinoPageScaffold
不是它的孩子,那么你需要将你称之为showSnackBar
函数的代码与Scaffold
的代码分离成一个单独的类,这里是SnackBarBody
,因为SnackBar
和Scaffold
可以'从相同的Build
函数调用。这是一个完整的工作示例:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() => runApp(SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SnackBar Demo',
home: CupertinoPageScaffold(
child: SnackBarPage(),
),
);
}
}
class SnackBarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SnackBarBody(),
);
}
}
class SnackBarBody extends StatefulWidget {
SnackBarBody({Key key,}):
super(key: key);
@override
_SnackBarBodyState createState() => new _SnackBarBodyState();
}
class _SnackBarBodyState extends State<SnackBarBody> {
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () {
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'),action: SnackBarAction(label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('Show SnackBar'),
),
);
}
}