您需要包含 a Scaffold
asCupertinoPageScaffold
不是它的子级,然后您需要将调用showSnackBar
函数的代码与 of的代码Scaffold
分开到一个单独的类中,SnackBarBody
因为 aSnackBar
和 aScaffold
不能从同一个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'),
),
);
}
}