Flutter
Theme.of
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.
Exercise 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.
Show example 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');
}
Test yourself
-
What does Theme.of(context) return?
- A Widget
- A Future
- A String
- A ThemeData object
Show answer
A ThemeData object — 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.
-
The Theme.of call
color: ____(context).colorScheme.primary,
Show answer
color: Theme.of(context).colorScheme.primary,
-
Theme.of parts
- Theme.of(context)
- Access to ThemeData
- colorScheme
- Color palette
- primary
- Primary color
- context
- Build context
Next lesson: Summary - ThemeData