要在下一页上显示snackbar,您可以将snackbar 函数传递给您正在导航到的页面,然后使用该答案中提到的方法在该页面的initState 中调用它:https://stackoverflow.com/a/50682918/16045128
WidgetsBinding.instance?.addPostFrameCallback((_) { widget.feedback?.call(); });
反馈小吃店演示:
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Icon(Icons.home),
SizedBox(height: 15),
Text(
'Home Page',
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Tooltip(
message: "Show Snackbar",
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondPage(
feedback: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('You have reached the second page.'),
duration: Duration(seconds: 3),
),
);
},
),
),
);
},
child: const Icon(Icons.check),
),
),
const SizedBox(width: 15),
Tooltip(
message: "Don't Show Snackbar",
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
},
child: const Icon(Icons.close),
),
),
],
),
);
}
}
class SecondPage extends StatefulWidget {
const SecondPage({Key? key, this.feedback}) : super(key: key);
final Function? feedback;
@override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback(
(_) {
widget.feedback?.call();
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Second Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Icon(Icons.two_k),
SizedBox(height: 15),
Text(
'Second Page',
),
],
),
),
);
}
}