Flutter-Cupertino Modal Bottom Sheet

這篇要教大家如何在 Flutter 實作 iOS13 開始支援的 Bottom Sheet 效果,如下圖 Uber Eats 就有使用這個效果

安裝 Plugin

首先要先安裝 modal_bottom_sheet

pubspec.yaml

調整 Route

為了要有動畫效果我們還要在需要使用此效果的 route 做一些處理

  1. 如果你使用 Navigator.of(context).push 寫法,需要改成

2. 如果你使用 onGenerateRoute 寫法,需要改成

MaterialWithModalsPageRoute 這個是 modal_bottom_sheet 提供的 class,作者有說明為何不能直接使用。

MaterialPageRoute and CupertinoPageRoute do not allow animated translation to/from routes that are not the same type.

實作 Bottom Sheet 內容

Bottom sheet 必須是 NavigatorCupertinoTabScaffold ,這邊用 Navigator 舉例。

最後我們使用 showCupertinoModalBottomSheet 就可以打開 bottom sheet

流程說明

以 Uber Eats 的 App 為例子,我們在首頁點選篩選器,篩選頁會被 Navigator push 到 stack 中,此時首頁則在篩選頁下面堆疊。再利用 modal_bottom_sheet 達到前後視差效果( Android 也可以達到此效果 )。

結語

利用 modal_bottom_sheet 可以輕鬆達到頁面前後視差效果,但使用後發現目前第一次觸發 bottom sheet 會有畫面卡一下的問題(之後皆不會),使用時可以考慮自己實作動畫效果 ( secondAnimation 參數可自定義 push/pop 動畫 ),以上若有錯誤也請歡迎指正唷。

--

--