Theme.of(context) Colors
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 22 of 30.
Buttons pick up the theme by themselves. Your own boxes do not: a Container with Colors.teal.shade100 stays that color whatever the theme is.
To color your own widgets from the theme, read it with Theme.of(context):
final colors = Theme.of(context).colorScheme;
Container(
color: colors.primaryContainer,
child: Text('Hi', style: TextStyle(color: colors.onPrimaryContainer)),
)The color scheme comes in pairs. primaryContainer is a soft fill, and onPrimaryContainer is the color of text on that fill, chosen to be easy to read. The same goes for primary and onPrimary, surface and onSurface.
Theme.of(context) finds the theme above the widget that asks. The theme is set by MaterialApp, so the context must be one below it, such as the build of HomeScreen. In MyApp's own build, which is above MaterialApp, it finds only Flutter's default purple.
Challenge
EasyColor the banner from the theme, so it follows any seed you choose:
- at the top of
HomeScreen'sbuild:final colors = Theme.of(context).colorScheme; - the banner's color:
colors.primaryContainer - its text color:
colors.onPrimaryContainer
Try it yourself
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),
),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Layout That Fits
1Sharing a Row
Expanded Fills the RowSharing Space With flexFlexible Hugs Its ChildSpacer Pushes Apart6Themes and Dark Mode
An App Theme From a SeedTheme.of(context) ColorsText Styles From the ThemeA Dark ThemeA Dark Mode SwitchPractice on your own: Online Flutter compiler