有没有办法将 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'),
),
);
}
}
关于dart - 将 SnackBar 与 CupertinoPageScaffold 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55382651/