Theme.of
- Flutter course
- Intermediate
- Lesson 89/99
- 4 min
Access theme values with Theme.of(context).
What is Theme.of?
Theme.of(context) lets you access the ThemeData in the current context. This way you can use theme colors and styles directly inside a widget. You reach the primary color with Theme.of(context).colorScheme.primary and the body style with Theme.of(context).textTheme.bodyLarge.
Text(
'Merhaba',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
),
)This is the main way to access the theme without passing it manually to widgets.
Accessing colorScheme and textTheme
With Theme.of(context) you access both colors and text styles. Theme.of(context).colorScheme.primary gives the primary color and Theme.of(context).textTheme.bodyLarge gives the large body style. You can bind these values directly to the style or color parameters of widgets.
final tema = Theme.of(context);
print(tema.colorScheme.primary);
print(tema.textTheme.bodyLarge);This access makes all widgets update automatically when the theme changes.
Practice Colored text with Theme.of
Define a StatelessWidget named RenkliYazi. Its build method should return a Text whose style parameter takes a TextStyle whose color field is Theme.of(context).colorScheme.primary. Print 'hazir' in main.
Starter code
import 'package:flutter/material.dart';
// RenkliYazi StatelessWidget tanımla
// build bir Text döndürsün
// Text'in rengi temadan gelsin
void main() {
// 'hazir' yazdır
}Sample solution
import 'package:flutter/material.dart';
class RenkliYazi extends StatelessWidget {
const RenkliYazi({super.key});
@override
Widget build(BuildContext context) {
return Text(
'Merhaba',
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
),
);
}
}
void main() {
print('hazir');
}Expected output
hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Theme.of(context) return?
- A Widget
- A Future
- A String
- A ThemeData object Correct answer
Explanation: Theme.of(context) returns the ThemeData object in that context; so you can access fields like colorScheme and textTheme. Widget, Future, and String are not ThemeData.
2 The Theme.of call
color: ____(context).colorScheme.primary,
color: Theme.of(context).colorScheme.primary,
Explanation: You access ThemeData with Theme.of(context). context.theme, ThemeData.of, and App.theme are not valid methods; the correct usage in Flutter is Theme.of.
3 Theme.of parts
| Term | Meaning |
|---|---|
Theme.of(context) |
Access to ThemeData |
colorScheme |
Color palette |
primary |
Primary color |
context |
Build context |