flutter 使用 WillPopScope

每個 WillPopScope 僅對當前組件生效,不可在 MaterialApp 上使用。 WillPopScope 返回值爲 false時,使用 Navigator.of(context).maybePop() 則不會退出當前路由(比如 AppBar 的退出)。而使用 Navigator.of(context).pop() 依然會退出。 WillPopScope 返回值爲 true時,未必會直接退出,還要根據當前頁是否是首頁來判斷。相關代碼截圖:

在未設置 WillPopScope 的情況下,快速連續點按 Navigator.of(context).maybePop() 可能會經過多次跳轉,直到會回到首頁。

示例代碼:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print('d will pop');
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text("home page"),
        ),
        body: Center(
          child: Column(
            children: [
              Text("Home"),
              TextButton(
                onPressed: () {
                  Navigator.pushNamed(context, "/me");
                },
                child: Text("Go To ME"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).maybePop();
                },
                child: Text("Exist HOME"),
              )
            ],
          ),
        ),
      ),
    );
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章