2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】AppBarを自作する

2
Posted at

はじめに

AppBarを自作しようとしていくつか詰まった部分があったので備忘録です。
手探りで実装を進めているのでとりあえずできた方法を共有します。

私の実装

table_calendarパッケージを利用してAppbarにカレンダーを追加しました。

スクリーンショット 2026-02-14 21.22.44.png

AppBarは単純なWidgetではない

単純にWidgetを作ろうとすると以下のようになると思います。

widget_example.dart
class WidgetExample extends StatefulWidget {
  const WidgetExample({super.key});

  @override
  State<WidgetExample> createState() => WidgetExampleState();
}

class WidgetExampleState extends State<WidgetExample> {
  // 処理...
}

しかし、AppBarの実装を見てみると以下のようになっています。

app_bar.dart
class AppBar extends StatefulWidget implements PreferredSizeWidget {
  AppBar({
    super.key,
    this.leading,
    // 中略
    this.actionsPadding,
    this.animateColor = false,
  }) : assert(elevation == null || elevation >= 0.0),
       preferredSize = _PreferredAppBarSize(toolbarHeight,bottom?.preferredSize.height);
  // 中略
  return preferredSize.height;
}

このように、AppBarには二つの特徴があります。

  • implements PreferredSizeWidgetがある
  • preferredSizeがある

これらが私の詰まった部分で、単純なWidgetではない箇所です。

PreferredSizeWidgetとは

一言でいうと、「制約がない場合に、そのウィジェットがなりたいサイズ(好ましいサイズ)」を返すことができるウィジェットのためのインターフェースです。

Flutterは親プロパティに合わせてサイズを変更しますが、AppBarのように固定のものはサイズを変えたくありません。そのため、PreferredSizeWidgetを利用し、preferredSizeを指定する必要があります。

implementsをすることでpreferredSizeを指定します!と宣言している

実装方法

ではどのように自作のAppBarを作ればいいでしょうか。

同じようにimplements PreferredSizeWidgetし、preferredSizeを設定すれば良いです。

original_appbar.dart
class OriginalAppBar extends StatefulWidget implements PreferredSizeWidget {
  // ここで高さを指定
  @override
  Size get preferredSize => const Size.fromHeight(120.0);

  @override
  State<CalendarAppBar> createState() => _CalendarAppBarState();
}

class OriginalAppBarState extends State<OriginalAppBar> {
  // 処理...
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?