來吧!Flutter(6)-Widget的骨架-Scaffold類別

Andy Lu
Flutter Taipei
Published in
5 min readJul 10, 2020

--

Scaffold 意思是鷹架,Scaffold 類別是 Flutter 中最常使用到的類別,可以在 Scaffold 類別中加上 AppBar, BottomBar, Drawer, FAB…。

建構子:

在建構子當中,有幾個 Widget 值得說明

appBar

將 appBar 作為參數傳入,將會在頁面上方顯示一個 App Bar,在 iOS 以及 Android 上略微不同。

左:Android, 右:iOS
//標題
title: Text('Scaffold Demo')
//前方按鈕
leading: IconButton(icon: Icon(Icons.menu))
//後方按鈕
action: <Widget>[
IconButton(icon: Icon(Icons.add_circle), onPressed: (){}),
IconButton(icon: Icon(Icons.more_vert), onPressed: (){}),
]
  • Scaffold 的背景顏色可以在 MaterialApp 中的 theme 設定 primaryColor,或是在 Scaffold 中設定 backgroundColor。兩個地方設定的差別在於,前者是全域參數,後者是區域參數。

Drawer

  • 將 Drawer 作為參數傳入,不需要在 AppBar 上設定 leading:IconButton,Scaffold 會在 AppBar 上自動出現目錄按鈕,點擊之後,便可以彈出 Drawer。
  • 預設是支援「在左邊的邊緣往左滑的手勢』開啟 Drawer,如果需要取消,則可以將 drawerEnableOpenDragGesture 設為 false。
左:Android, 右: iOS

上面的範例看到的 Drawer 是一片白,因為我們尚未在 Drawer 的 child 增加 Widget。

Action:新增 Drawer 內容

利用 ListView 實現 Drawer 的內容,其中 Drawer 上方使用的是 DrawerHeader widget,下方的按鈕皆是使用 ListTile。

左:Android, 右: iOS

endDrawer

與 Drawer 相同,不過出現的位置是由右至左。AppBar 上的目錄按鈕也是出現在右邊。這邊就不多做敘述。

floatingActionButton(FAB)

在畫面左下角會出現一個圓形的按鈕。可以用 FAB 操作該畫面的重要行為。

左:Android, 右:iOS

FloatingActionButton.extended

Flutter 在 FloatingActionButton 類別中,提供了加大型的 FAB,呼叫 FloatingActionButton.extend 即可產生。

Action:使用 FloatingActionButton.extended 加上含有文字的 FAB

左:Android, 右:iOS

Bottom Navigation Bar

  • 在畫面的下方顯示導覽列,最少需要兩個按鈕。
  • items 使用的是 BottomNavigationBarItem。
  • onTap 會回傳 index,這個 index 是現在按下去 BottomNavigationBarItem 的index,將 index 存起來,並且利用 setState 設定。
  • currentIndex 會根據傳進來的 index 值,決定哪一個 BottomNavigationBarItem 是 Enable。
  • 最後,這個 Parent widget 需要改成 StatefulWidget,才能夠在 onTap 使用 setState()。

Bottom Sheet

Action:Demo Bottom Sheet,利用 Column 加上兩個 ListTile 呈現

左:Android, 右:iOS

Body

最後是 body,將主要的畫面寫在 body,例如上面範例示範的 Container 加上 Text Widget。

Container(
child: Text('Hello Scaffold')
)

小記

Flutter 提供了 Scaffold 類別,可以輕易的寫出 material design 的畫面,不論是 App Bar, Drawer, FAB… 都已經定義在 Scaffold 裡面,只需要依需求加上所需的物件。

接下來的章節,將繼續介紹 Body 裡面可以使用哪些 Widget。

謝謝收看

--

--

Andy Lu
Flutter Taipei

Android/Flutter developer, Kotlin Expert, like to learn and share.