Theme.of контекста в Flutter
Тема, заданная у MaterialApp,
доступна любому потомку через
Theme.of(context).
Так виджет не дублирует цвета и шрифты
и реагирует на смену темы.
Чаще всего берут Theme.of(context).textTheme
для Text и
Theme.of(context).colorScheme
для фона, иконок и кнопок. Пары
primaryContainer и
onPrimaryContainer уже подобраны
по контрасту. Если нужен весь объект
темы - Theme.of(context)
возвращает ThemeData:
import 'package:flutter/material.dart';
void main() {
runApp(const ThemeOfApp());
}
class ThemeOfApp extends StatelessWidget {
const ThemeOfApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const ThemeOfDemoPage(),
);
}
}
class ThemeOfDemoPage extends StatelessWidget {
const ThemeOfDemoPage({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final text = theme.textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Theme.of')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Title', style: text.titleLarge),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: scheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Text on primaryContainer',
style: TextStyle(color: scheme.onPrimaryContainer),
),
),
],
),
),
);
}
}
Соберите карточку только через
Theme.of(context):
final theme = Theme.of(context);
Container(
color: theme.colorScheme.surfaceContainerHighest,
child: ListTile(
leading: Icon(
Icons.star,
color: theme.colorScheme.primary,
),
title: Text(
'Title',
style: theme.textTheme.titleMedium,
),
),
)