LoginSignup
1
1

【Flutter】ダイアログの背景色が設定通りにならない

Last updated at Posted at 2023-12-20

備忘録として残します。

ダイアログの背景色が真っ白に出来ない・・・

真っ白なダイアログを出したい場面があったので、
下記のようなコードでbackgroundColorColors.whiteを設定しました。

Dialog(
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(16.0),
        ),
      ),
      insetPadding: const EdgeInsets.symmetric(
        horizontal: 26,
      ),
      child: // 省略
);

すると、下記のようになりました。
ちょっと紫がかっています。

原因

Dialogの引数surfaceTintColorが影響しています。

ドキュメントを読むと、下記の記載があります。

If null and ThemeData.useMaterial3 is true
then ThemeData's ColorScheme.surfaceTint will be used.

つまり下記の2つの条件が満たされる場合、
ThemeData.surfaceTintが利用されるようになっているようです。

  • Dialogの引数であるsurfaceTintColorが設定されていない。
  • ThemeData.useMaterial3trueになっている。

余談: ThemeDataはどこで定義されている?

MyApp内で定義されていることが多いかと思います!

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), <- これ
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

ここでdeepPurpleが指定されていた影響で
ダイアログが紫がかっていたんですねぇ。

結論

surfaceTintColorColors.transparentを設定すると、
意図した背景色を反映させることが出来ます。

Dialog(
      backgroundColor: Colors.white,
+     surfaceTintColor: Colors.transparent,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(16.0),
        ),
      ),
      insetPadding: const EdgeInsets.symmetric(
        horizontal: 26,
      ),
      child: // 省略
);

surfaceTintColorあり
surfaceTintColorなし

最後に

新しいWidgetを使うときは、ドキュメントを読みましょう。(自戒)

1
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
1
1