簡體   English   中英

如何在顫動中攔截AppBar中的后退按鈕

[英]How to intercept back button in AppBar in flutter

當第 1 頁從第 2 頁返回時,我正在使用攔截器https://pub.dartlang.org/packages/back_button_interceptor執行方法。

如果我使用設備返回按鈕從第 2 頁返回到第 1 頁,則執行該方法。

但是,如果我使用 appBar 上的箭頭按鈕從第 2 頁返回到第 1 頁,我將無法執行該方法。

后退箭頭按鈕功能如何默認為設備后退按鈕?

您可以使用 WillPopScope 在第 2 頁上包圍您的腳手架,將 onWillPop 設置為 false 以防止頁面被系統彈出,然后將您自己的后退按鈕添加到應用程序欄的前導小部件中並在那里執行您的彈出。

@override
Widget build(BuildContext context) {
  return new WillPopScope(
    onWillPop: () async => false,
    child: new Scaffold(
      appBar: new AppBar(
        title: new Text("data"),
        leading: new IconButton(
          icon: new Icon(Icons.ac_unit),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
    ),
  );
}

這篇文章的答案代碼

編輯:添加到第 2 頁以控制導航

除了上面的代碼,您還要將下面的代碼添加到第 2 頁。更改

Navigator.of(context).pop() 

Navigator.of(context).pop('upload_files')

然后在您導航的第 1 頁中,您將等待導航並使用從第 2 頁上的彈出窗口返回的結果並運行您的邏輯

var navigationResult = await Navigator.push(
        context,
        new MaterialPageRoute(
            builder: (context) => Page2()));


 if(navigationResult == 'upload_files') {
    uploadFiles(); // Perform your custom functionality here.
 }

AppBar的默認后退按鈕是來自material.dart BackButton小部件。 你可以手動創建它並傳遞你自己的onPressed來做你想做的事:

return Scaffold(
  appBar: AppBar(
    leading: BackButton(onPressed: _onBackPressed),
    title: Text('Title'),
  ),
  body: Container(),
);

如果您沒有在AppBar指定leading ,那么它會使用執行Navigator.maybePop(context)的處理程序創建一個BackButton

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM