AppBar actions アイコンに背景色を設定したい

Icons.account_circle の人間の部分の色だけ変えたい。が、それをやるのは結構ややこしい。普通にアイコンを設置すると人間部分は透過となっている。

After のように人間部分に色を設定する。

Before After
f:id:star__hoshi:20220405085334p:plain f:id:star__hoshi:20220405085343p:plain

最初のコード

普通に actions に IconButton を入れてるだけ

    return Scaffold(
      appBar: AppBar(
        actions: [
            IconButton(
              onPressed: () {},
              icon: const Icon(
                Icons.account_circle,
                size: 30,
            ),
          ),
        ],
      ),
      body: Container(),
    );

Container で囲って背景色を設定してみる

しかしなんかズレて見切れてしまう。

f:id:star__hoshi:20220405085504p:plain

    return Scaffold(
      appBar: AppBar(
        actions: [
          Container(
            color: Colors.black,
            width: 30,
            height: 30,
            child: IconButton(
              onPressed: () {},
              icon: const Icon(
                Icons.account_circle,
                size: 2,
              ),
            ),
          ),
        ],
      ),
      body: Container(),
    );

Stack で裏側に Container を置く

SizedBox で箱を作り、その中に Stack で黒の背景をおきその上にIconButtonを乗っけている。タップフィードバックも問題なし。

f:id:star__hoshi:20220405085546p:plain

return Scaffold(
      appBar: AppBar(
        actions: [
          SizedBox(
            width: 48,
            height: 48,
            child: Stack(
              children: [
                Center(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(13),
                      color: Colors.black,
                    ),
                    width: 22,
                    height: 22,
                  ),
                ),
                Center(
                  child: IconButton(
                    onPressed: () {},
                    icon: const Icon(
                      Icons.account_circle,
                      size: 28,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      body: Container(),
    );

これで AppBar の Icons.account_circle の人間部分の色をつけることができた。(最初から画像で用意した方が早そう)

注意事項として、SliverAppBar などで上にスクロールするとアイコンの透過率が変わるが今回背景色に設定した部分の色は変わらないので注意。