Theme.of(context) 中的颜色
本课属于 Coddy Flutter 学习旅程的“适配不同屏幕的布局”单元。第 22 课,共 30 课。
按钮会自动采用主题。你自己的容器不会:无论主题是什么,使用 Colors.teal.shade100 的 Container 都会保持这个颜色。
要用主题为自己的组件设置颜色,可以通过 Theme.of(context) 读取主题:
final colors = Theme.of(context).colorScheme;
Container(
color: colors.primaryContainer,
child: Text('Hi', style: TextStyle(color: colors.onPrimaryContainer)),
)配色方案中的颜色是成对出现的。primaryContainer 是柔和的填充色,而 onPrimaryContainer 是显示在这种填充色上的文字颜色,经过选择,易于阅读。primary 和 onPrimary、surface 和 onSurface 也是如此。
Theme.of(context) 会查找使用它的组件上方的主题。主题由 MaterialApp 设置,因此 context 必须来自它下方的位置,例如 HomeScreen 的 build 方法。在 MyApp 自己的 build 方法中,由于它位于 MaterialApp 上方,因此只能找到 Flutter 默认的紫色主题。
挑战
简单使用主题为横幅着色,这样它就会跟随你选择的任意种子颜色:
- 在
HomeScreen的build开头:final colors = Theme.of(context).colorScheme; - 横幅的颜色:
colors.primaryContainer - 横幅文字的颜色:
colors.onPrimaryContainer
亲手试试
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(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Bookshelf')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.teal.shade100,
borderRadius: BorderRadius.circular(16),
),
child: Text(
'You read 12 books this year',
style: TextStyle(fontSize: 20, color: Colors.teal.shade900),
),
),
],
),
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
适配不同屏幕的布局中的所有课
自己练习: Flutter 在线编译器