11. 页面跳转返回,并回传值

1. 跳转返回后,接收子页面传来的值

这次我们在父级页面,点击按钮,进入子页面,点击子页面的不同按钮,返回父页面的时候,弹出从子页面返回的信息

2. 父级页面
void main() {
  runApp(MaterialApp(
    title: "跳转页面并返回值",
    home: Scaffold(
      appBar: AppBar(
        title: const Text("去找小姐姐"),
      ),
      body: Center(
          child: Button()
      ),
    ),
  ));
}

class Button extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: const Text("去找小姐姐"),
      onPressed: () {
        navigateToXiaoJieJie(context);
      },
    );
  }

}

navigateToXiaoJieJie(BuildContext context) async {

  final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => XiaoJieJie()));

  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("$result")));
}
3. 子页面
class XiaoJieJie extends StatelessWidget {

  const XiaoJieJie({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("人物列表"),
        ),
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                  child: const Text("王语嫣"),
                  onPressed: () {
                    Navigator.pop(context, "王语嫣:18549806226");
                  }),
              ElevatedButton(
                  child: const Text("王菲"),
                  onPressed: () {
                    Navigator.pop(context, "王菲:18549806228");
                  }),
            ],
          ),
        ));
  }
}

推荐阅读更多精彩内容