# flutter路由返回的差异

flutter中提供了两个路由返回的api:Navigator.pop()、Navigator.maybePop(),下面我们来分析一下它们的区别

import 'package:flutter/material.dart';
class PopMaybeDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "pop与maybePop的区别",
      home: Scaffold(
          appBar: AppBar(title: Text("pop与maybePop的区别")),
          body: Container(
            alignment: Alignment.center,
            child:Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  child: Text("Navigator.pop()"),
                  onPressed: (){
                    Navigator.pop(context);
                  },
                ),
                RaisedButton(
                  onPressed: (){
                    Navigator.maybePop(context);
                  },
                  child: Text("Navigator.maybePop()"),
                )
              ],
            )
          ),
      ),
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

当路由堆栈中只剩下一个页面时,调用Navigator.maybePop()会发现页面没有反应,而调用Navigator.pop()时,最后一个flutter页面也被移除了此时只剩下了一个android的原生activity。

# 总结

  1. Navigator.maybePop() :当路由堆栈中仅剩下一个页面是,该操作什么也不干
  2. Navigator.pop():只要路由堆栈中还有页面就pop