在 ThemeData 中集中管理颜色和排版,用 ColorScheme.fromSeed 生成一套 Material 3 配色,并轻松提供深色模式。
在 Kodokon 中打开本课不再逐个 widget 地设置样式,是一个专业上的里程碑:ThemeData 会为整个应用集中管理颜色、排版和形状。有了 Material 3(自 Flutter 3.16 起默认启用),一切都从 ColorScheme 开始:ColorScheme.fromSeed 会从单单一种种子色派生出一套完整、和谐且无障碍的配色。
import 'package:flutter/material.dart';
void main() {
runApp(const ShopApp());
}
class ShopApp extends StatelessWidget {
const ShopApp({super.key});
@override
Widget build(BuildContext context) {
const seed = Colors.teal;
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
),
themeMode: ThemeMode.system,
home: Scaffold(
appBar: AppBar(title: const Text('Shop')),
body: const Center(child: Text('Welcome')),
),
);
}
}在你的 widget 内部,不要重新发明任何东西:用 Theme.of(context) 读取当前的主题。colorScheme 暴露出一批语义化的角色(primary、onPrimary、primaryContainer、surface 等),textTheme 则暴露出一批具名样式(titleMedium、bodyLarge 等)。这样写出来的 widget 会自动适配浅色主题和深色主题。
import 'package:flutter/material.dart';
class PriceTag extends StatelessWidget {
const PriceTag({super.key, required this.price});
final double price;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final text = Theme.of(context).textTheme;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: colors.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$price €',
style: text.titleMedium?.copyWith(
color: colors.onPrimaryContainer,
),
),
);
}
}想更进一步,就配置组件主题:每一类 widget(应用栏、按钮、输入框)都能在 ThemeData 里接受一份专属主题。你只需一次性定义按钮的内边距或标题的居中方式,之后每个实例都会继承它,而无需任何一处局部样式。
import 'package:flutter/material.dart';
final ThemeData appTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
),
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
);