Flutter: Theming & Styling System
Theme is an app's wardrobe — a unified style lets users recognize your brand at a glance.
📋 Prerequisites: You should already be familiar with
- Lesson 15: Animation System
1. What You'll Learn
- ThemeData full configuration: colorScheme, textTheme, appBarTheme, cardTheme
- Dynamic theme switching: Light / Dark / custom brand themes (Riverpod-managed)
- ThemeExtension
<T>custom theme token extensions - Component-level theme overrides: Theme(data: ..., child: ...)
- ShopApp: brand theme system (brand color + dark mode + large-text accessibility)
2. A Real Story of Brand Chaos
(1) The Pain Point: A Hundred Pages, A Hundred Blues
Bob's ShopApp is developed by 3 developers, each defining their own colors: Colors.blue, Color(0xFF2196F3), Color(0xFF1976D2). Across 100 pages there are 12 different blues, and button corner radii come in 4px, 8px, and 12px varieties. Dark mode is even more chaotic — some use Colors.white text on dark backgrounds, others use Colors.grey[300]. Brand recognition is practically nonexistent.
(2) The ThemeData Solution
ThemeData uniformly defines all colors, fonts, and shapes — components automatically derive styles from the theme, and a single change takes effect globally.
import 'package:flutter/material.dart';
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Color(0xFF0066CC)),
appBarTheme: const AppBarTheme(centerTitle: true),
cardTheme: CardThemeData(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
),
)
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(3) The Payoff: Brand Unity + Global Switch
After Bob defined the ShopApp brand theme, all pages automatically shared a unified style. Dark mode required only a ThemeData switch — no per-page changes needed.
3. ThemeData Configuration System
graph TD
MT[MaterialApp.theme] --> TD[ThemeData]
TD --> CS[ColorScheme]
TD --> TM[TextTheme]
TD --> AT[AppBarTheme]
TD --> CT[CardTheme]
TD --> TE[ThemeExtension]
TE --> Brand[BrandTokens]
CS --> |light| Light[Light Scheme]
CS --> |dark| Dark[Dark Scheme]
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(1) ColorScheme Color System
| Color Role | Usage | Example |
|---|---|---|
primary |
Primary brand color (buttons/tabs) | #0066CC |
onPrimary |
Text on primary color | #FFFFFF |
secondary |
Accent color | #FF6B35 |
surface |
Card/background | #FFFFFF/#1C1C1E |
onSurface |
Text on surface | #1C1C1E/#FFFFFF |
error |
Error color | #B3261E |
outline |
Borders/dividers | #79747E |
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: ShopApp brand color definitions
import 'package:flutter/material.dart';
class ShopAppColors {
static const primary = Color(0xFF0066CC);
static const secondary = Color(0xFFFF6B35);
static const surface = Color(0xFFFFFFFF);
static const onSurface = Color(0xFF1C1C1E);
static final light = ColorScheme.light(
primary: primary,
secondary: secondary,
surface: surface,
onSurface: onSurface,
error: const Color(0xFFB3261E),
);
static final dark = ColorScheme.dark(
primary: const Color(0xFF80B3FF),
secondary: const Color(0xFFFF9B75),
surface: const Color(0xFF1C1C1E),
onSurface: const Color(0xFFE6E6E6),
error: const Color(0xFFF2B8B5),
);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
4. ThemeData Full Configuration
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: ShopApp complete theme
import 'package:flutter/material.dart';
// Custom class definition source:
// - ShopAppColors: see Section 3 brand color definitions in this lesson
ThemeData shopAppLightTheme(ColorScheme colorScheme) => ThemeData(
useMaterial3: true,
colorScheme: colorScheme,
// AppBar
appBarTheme: AppBarTheme(
centerTitle: true,
elevation: 0,
backgroundColor: colorScheme.surface,
foregroundColor: colorScheme.onSurface,
),
// Card
cardTheme: CardThemeData(
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
clipBehavior: Clip.antiAlias,
),
// Elevated/Filled Button
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
),
// Input
inputDecorationTheme: InputDecorationTheme(
filled: true,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
// Bottom Nav
navigationBarTheme: NavigationBarThemeData(
indicatorColor: colorScheme.primary.withOpacity(0.1),
),
// Text
textTheme: ThemeData.light().textTheme.apply(
fontFamily: 'Roboto',
),
);
ThemeData shopAppDarkTheme(ColorScheme colorScheme) => shopAppLightTheme(colorScheme).copyWith(
brightness: Brightness.dark,
scaffoldBackgroundColor: const Color(0xFF0D0D0F),
);
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
5. Dynamic Theme Switching
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Riverpod theme management
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ⚙️ Install dependencies: flutter pub add flutter_riverpod riverpod_annotation shared_preferences
// ⚙️ Dev dependencies: flutter pub add --dev riverpod_generator build_runner
// Custom class definition source:
// - shopAppLightTheme/shopAppDarkTheme: see Section 4 in this lesson
// - ShopAppColors: see Section 3 brand color definitions in this lesson
enum AppThemeMode { light, dark, system }
@riverpod
class ThemeModeNotifier extends _$ThemeModeNotifier {
@override
AppThemeMode build() => AppThemeMode.system;
void setMode(AppThemeMode mode) {
state = mode;
SharedPreferences.getInstance().then((prefs) => prefs.setString('theme_mode', mode.name));
}
ThemeMode get flutterThemeMode => switch (state) {
AppThemeMode.light => ThemeMode.light,
AppThemeMode.dark => ThemeMode.dark,
AppThemeMode.system => ThemeMode.system,
};
}
// In MaterialApp
class ShopApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final themeMode = ref.watch(themeModeNotifierProvider).flutterThemeMode;
return MaterialApp(
theme: shopAppLightTheme(ShopAppColors.light),
darkTheme: shopAppDarkTheme(ShopAppColors.dark),
themeMode: themeMode,
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Theme switching settings page
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// ⚙️ Install dependencies: flutter pub add flutter_riverpod
// Custom class definition source:
// - AppThemeMode/themeModeNotifierProvider: see Section 5 Riverpod theme management in this lesson
class ThemeSettingsPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final current = ref.watch(themeModeNotifierProvider);
return Scaffold(
appBar: AppBar(title: const Text('Appearance')),
body: ListView(children: AppThemeMode.values.map((mode) {
final label = switch (mode) {
AppThemeMode.light => 'Light',
AppThemeMode.dark => 'Dark',
AppThemeMode.system => 'System',
};
return RadioListTile<AppThemeMode>(
title: Text(label),
value: mode,
groupValue: current,
onChanged: (v) => ref.read(themeModeNotifierProvider.notifier).setMode(v!),
);
}).toList()),
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
6. ThemeExtension Custom Extensions
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Brand token extension
import 'package:flutter/material.dart';
import 'dart:ui';
// Custom class definition source: BrandTokens is a custom ThemeExtension in this lesson
class BrandTokens extends ThemeExtension<BrandTokens> {
final Color salePrice;
final Color discount;
final Color rating;
final double cardRadius;
final double productImageRatio;
const BrandTokens({
this.salePrice = Colors.green,
this.discount = Colors.red,
this.rating = Colors.amber,
this.cardRadius = 12,
this.productImageRatio = 0.75,
});
@override
BrandTokens copyWith({Color? salePrice, Color? discount, Color? rating,
double? cardRadius, double? productImageRatio}) {
return BrandTokens(
salePrice: salePrice ?? this.salePrice,
discount: discount ?? this.discount,
rating: rating ?? this.rating,
cardRadius: cardRadius ?? this.cardRadius,
productImageRatio: productImageRatio ?? this.productImageRatio,
);
}
@override
BrandTokens lerp(covariant BrandTokens? other, double t) {
if (other == null) return this;
return BrandTokens(
salePrice: Color.lerp(salePrice, other.salePrice, t)!,
discount: Color.lerp(discount, other.discount, t)!,
rating: Color.lerp(rating, other.rating, t)!,
cardRadius: lerpDouble(cardRadius, other.cardRadius, t)!,
productImageRatio: lerpDouble(productImageRatio, other.productImageRatio, t)!,
);
}
}
// Use in ThemeData
ThemeData(extensions: const [BrandTokens()])
// Access in widget
final brand = Theme.of(context).extension<BrandTokens>()!;
Text('\$99.99', style: TextStyle(color: brand.salePrice));
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
7. Accessibility Large-Text Mode
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Responsive text scaling
import 'package:flutter/material.dart';
class AccessibleText extends StatelessWidget {
final String text;
final TextStyle? style;
const AccessibleText(this.text, {super.key, this.style});
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
// Clamp text scale factor for accessibility
final scaleFactor = mediaQuery.textScaleFactor.clamp(0.8, 2.0);
return MediaQuery(
data: mediaQuery.copyWith(textScaleFactor: scaleFactor),
child: Text(text, style: style),
);
}
}
// Global text scale limit in MaterialApp
builder: (context, child) {
final mq = MediaQuery.of(context);
return MediaQuery(
data: mq.copyWith(textScaleFactor: mq.textScaleFactor.clamp(0.8, 1.5)),
child: child!,
);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
8. Complete Example: ShopApp Theme System
import 'package:flutter/material.dart';
// Custom class definition source:
// - ShopAppColors: see Section 3 brand color definitions in this lesson
// - BrandTokens: see Section 6 ThemeExtension in this lesson
class ShopAppTheme {
static ThemeData light() => ThemeData(
useMaterial3: true,
colorScheme: ShopAppColors.light,
extensions: const [BrandTokens()],
appBarTheme: const AppBarTheme(centerTitle: true, elevation: 0),
cardTheme: CardThemeData(elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))),
inputDecorationTheme: InputDecorationTheme(filled: true,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8))),
);
static ThemeData dark() => ThemeData(
useMaterial3: true,
colorScheme: ShopAppColors.dark,
extensions: const [BrandTokens(
salePrice: Color(0xFF4CAF50),
discount: Color(0xFFEF5350),
)],
appBarTheme: const AppBarTheme(centerTitle: true, elevation: 0),
scaffoldBackgroundColor: const Color(0xFF0D0D0F),
cardTheme: CardThemeData(elevation: 1, color: const Color(0xFF1C1C1E),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
❓ FAQ
final theme = Theme.of(context);, then reuse the theme variable.Theme(data: Theme.of(context).copyWith(...), child: widget).📖 Summary
- ThemeData uniformly manages colors, fonts, and shapes — one change, global effect
- ColorScheme defines semantic color roles, auto-adapting to Light/Dark
- Riverpod manages theme switching state, SharedPreferences persists the choice
- ThemeExtension extends custom brand tokens (sale colors/corner radii/ratios)
- MediaQuery.textScaleFactor limits text scaling, ensuring accessibility
📝 Exercises
- Basic (Difficulty ⭐): Use ColorScheme.fromSeed to create a brand color theme and apply it to MaterialApp.
- Intermediate (Difficulty ⭐⭐): Implement Light/Dark/System three-mode switching using Riverpod + SharedPreferences persistence.
- Challenge (Difficulty ⭐⭐⭐): Create a complete ShopApp theme system: BrandTokens extension + Light/Dark dual themes + large-text accessibility mode + component-level theme overrides.