Flutter 返回原生的上一頁

最近寫 Flutter 頁面需要嵌入原生頁面,發(fā)現(xiàn) Flutter 中似乎沒有返回上一頁的功能,在 Android 中就是返回上一個(gè) activity。

眾所周知,F(xiàn)lutter 嵌入原生 Android 時(shí),需要用一個(gè)空的 activity 來承載,F(xiàn)lutter 作為一個(gè) view 添加進(jìn)當(dāng)前的 activity,從 Flutter 的角度來說,這個(gè) FlutterView 就是一個(gè) App 了,所以不能返回其實(shí)是個(gè)正常邏輯,因?yàn)樗呀?jīng)在第一頁了,所以我們其實(shí)要做的是退出當(dāng)前的 Flutter App。

現(xiàn)在我的 Flutter 頁面上有一個(gè)導(dǎo)航條,如下圖:


截屏2019-10-22下午7.24.43.png

我需要為左邊的返回鍵實(shí)現(xiàn)返回上一個(gè)原生頁面的功能,一開始想到的是使用Flutter 的 Channel,然后分別在 Android、iOS 原生代碼里接收消息,分別實(shí)現(xiàn)返回。但是這樣太麻煩了,應(yīng)該有個(gè)更簡單的方法,畢竟我只是想退出一下。

后來我找到了這個(gè)方法 SystemNavigator.pop(),看一下它的源碼:

class SystemNavigator {
  SystemNavigator._();

  /// Instructs the system navigator to remove this activity from the stack and
  /// return to the previous activity.
  ///
  /// On iOS, calls to this method are ignored because Apple's human interface
  /// guidelines state that applications should not exit themselves.
  ///
  /// This method should be preferred over calling `dart:io`'s [exit] method, as
  /// the latter may cause the underlying platform to act as if the application
  /// had crashed.
  static Future<void> pop() async {
    await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop');
  }
}

可以看到注釋上寫的很清楚,這個(gè)就是用來返回上一個(gè) activity 的,但是上面也提到了,在 iOS 平臺(tái)上這個(gè)方法會(huì)被忽略,因?yàn)?iOS 里沒有退出 App 的說法。另外還提到這個(gè)方法要比直接調(diào)用 Dart 的 exit 要好,因?yàn)?exit 命令會(huì)讓底層表現(xiàn)的像程序崩潰一樣(但是好像也沒說 exit 會(huì)讓宿主 app 異常),所以我們對平臺(tái)做一下兼容:

onPressed: () {
  if(Platform.isAndroid){
    SystemNavigator.pop();
  } else {
    exit(0);
  }
},

測了一下,這樣寫是OK的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容