😊

[Flutter]Drawer の実装

に公開

はじめに

今回は設定ページなどが横から出てくる Drawer についてまとめてみました。アプリの規模が大きくからほど、設定やアカウント情報の変更で役に立つ drawer。
flutter で簡単に実装ができるのでその実装方法についてまとめてみました。

Drawer の実装

Drawer はアプリの左右からスライドして表示されたり、ハンバーガーアイコンと呼ばれる横三本線のマークを押すと出てきたりするメニューのことですが、Scaffold の中に入れて使うWidgetです。
Widget内では、ColumnListView と合わせて使うことが多いです。
以下はコード例です。

Scaffold(
      drawer: Drawer(
        child: ListView(
          children: [
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue),
              child: Text(
                'メニュー',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            ListTile(
              leading: Icon(Icons.home),
              title: Text('ホーム'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.settings),
              title: Text('設定'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      body: Center(chilld: Text('Hello World!')),
    );

endDrawer

endDrawer とは右側に drawer を出すことです。
基本的な部分はほとんど同じですが、'drawer' ではなく 'endDrawer' を使うことで実装できます。
以下はそのコード例です。

Scaffold(
      endDrawer: Drawer(
        child: ListView(
          children: [
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue),
              child: Text(
                'メニュー',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            ListTile(
              leading: Icon(Icons.home),
              title: Text('ホーム'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.settings),
              title: Text('設定'),
              onTap: () {
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      body: Center(chilld: Text('おはよう')),
    );

UserAccountDrawerHeader

UserAccountDrawerHeader とは、ユーザーのプロフィール情報を表示するためのヘッダーで、主にユーザー名・メールアドレス・プロフィール画像を見やすく表示するために使われます。
以下はそのコード例です。

UserAccountsDrawerHeader(
  accountName: Text('ぽちぽち太郎'),
  accountEmail: Text('taro@example.com'),
  currentAccountPicture: CircleAvatar(
    backgroundImage: NetworkImage('https://example.com/profile.jpg'),
  ),
  decoration: BoxDecoration(
    color: Colors.blue,
  ),
)

最後に

今回は Drawer についてまとめたことを書いてみました。
実装するためのコードは非常にわかりやすく、私も練習のために Spotify の UI を再現する際に利用しました。
UI 部分で知っていたらすぐに実装できる Widget 等を今後も勉強しながら記事にできたらと思っています。

ぽちぽちのつどい

Discussion