Sub topic 1
What Material 3 means in Flutter
Material 3 (often written M3) is the current version of Google's Material Design system. It defines how buttons, cards, app bars, and text look and respond. In Flutter, it is implemented in the material library and controlled through ThemeData. Since Flutter 3.16, useMaterial3 defaults to true, so new apps get Material 3 without extra setup. Set useMaterial3: false only when maintaining an older app that depends on Material 2 styling.
Prerequisites
You should know Dart null safety, how to build widget trees with StatelessWidget, and how MaterialApp and Scaffold fit together. Familiarity with BuildContext helps, because Theme.of(context) depends on it.
ThemeData: the single source of theme values
ThemeData is an object that holds every visual value for a part of your app: colors, text styles, and component defaults. Pass it to MaterialApp.theme, and every descendant widget inherits it. Changing one value there updates the whole app, so you avoid repeating styles on each widget.
Reading theme values with Theme.of(context)
Widgets should read colors from the theme instead of hard-coding values like Color(0xFF6750A4). Theme.of(context) returns the nearest ThemeData above the widget in the tree. When the light or dark theme changes, the widget rebuilds with the new values.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6750A4)),
),
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(title: const Text('Material 3')),
body: Center(
child: Container(
padding: const EdgeInsets.all(16),
color: colors.primaryContainer,
child: Text(
'Hello, theme',
style: TextStyle(color: colors.onPrimaryContainer),
),
),
),
);
}
}ColorScheme and its color roles
A ColorScheme groups colors by role rather than by name. Each role has a paired "on" color for content placed on top of it. For example, primary is the main brand color, and onPrimary is the color for text or icons drawn on it. Other roles include primaryContainer, secondary, surface, onSurface, and error.
Exercise
Why should a widget use colors.onPrimaryContainer for its text instead of a fixed black color?
Show answer
The "on" role is chosen to contrast with its paired container color in both light and dark schemes. A fixed color can become unreadable when the theme changes.