Flutter3でMaterial3とdark modeを同時に使う
最終更新から4年以上たっています。ライブラリのバージョンや手順が変わっている可能性があります。
こんにちは。趣味グラマのNobu(@nm_aru)です。
先日、Flutter3と一緒にMaterial3への対応も発表されました。
Material3を使うには、Flutterのバージョンを3に上げるだけでは駄目で、ThemeDataのパラメータで指定してあげる必要があります。
私の場合は、ThemeDataでlight()やdark()を使っていたのですが、Material3と同時に使う方法が一瞬分からず悩んだので、備忘録として残しておきます。
Material3を使うにはuseMaterial3: trueを指定するだけ
// Flutter2でlight()とdark()を使っているパターン
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.system
home: MyApp()
);
}
}
// Flutter3でMaterial3とlight、darkを一緒に使うパターン
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true, brightness: Brightness.light),
darkTheme: ThemeData(useMaterial3: true, brightness: Brightness.dark),
themeMode: ThemeMode.system
home: MyApp()
);
}
}ドキュメントを見れば分かりますが、light()やdark()はコンストラクタで、結局中でbrightnessを指定してるだけでした。
ThemeData.light constructor - ThemeData - material library - Dart API
API docs for the ThemeData.light constructor from Class ThemeData from the material library, for the Dart programming la...
ThemeData.dark constructor - ThemeData - material library - Dart API
API docs for the ThemeData.dark constructor from Class ThemeData from the material library, for the Dart programming lan...
まとめ
Material3にしてみたところ、FABが角の丸い四角ボタンになったり、AppBarの色が変わったり、全体的に優しい雰囲気になった気がします。
それにしても、Flutterの進化のスピードは凄く早くて、個人開発をする上では楽しさ満載です。
Flutter の記事
コメントの受け付けは終了しました。ご意見・ご質問は X(@nm_aru)へどうぞ。


