くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

FlutterのAppBarをカスタマイズする

背景色を変える

AppBarbackgroundColorで指定。

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text("MyAppBar"),
      backgroundColor: Colors.white,
    );
  }
}

文字色を変える

AppBarstyleで指定。

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text(
        "MyAppBar",
        style: TextStyle(color: Colors.red),
      ),
    );
  }
}

下の影をなくす

AppBarelevationを0に指定。

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text("MyAppBar"),
      elevation: 0,
    );
  }
}

下線を引く

AppBarbottomで指定

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    final double lineHeight = 4;
    return AppBar(
      title: Text("MyAppBar"),
      bottom: PreferredSize(
          child: Container(height: lineHeight, color: Colors.red),
          preferredSize: Size.fromHeight(lineHeight)),
    );
  }
}

PreferredSizeは優先されるサイズを指定できるWidget
PreferredSize class - widgets library - Dart API

タイトルの左の余白を調整する

AppBartitleSpacingで指定

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text("MyAppBar"),
      titleSpacing: 0,
    );
  }
}

タイトルを画像にする

AppBartitleImageを指定

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Image.asset(
        "assets/images/logo.png",
        height: 40,
        fit: BoxFit.contain,
      ),
    );
  }
}

以上!! 増えたら、また追加する(´ω`)

参考にしたサイト様