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

1. What You'll Learn


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.

DART
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))),
  ),
)
TEXT
> 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

100%
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]
TEXT
> 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

TEXT
> 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

DART
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),
  );
}
TEXT
> 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

TEXT
> 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

DART
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),
);
TEXT
> 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

TEXT
> 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

DART
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,
    );
  }
}
TEXT
> 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

TEXT
> 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

DART
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()),
    );
  }
}
TEXT
> 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

TEXT
> 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

DART
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));
TEXT
> 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

TEXT
> 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

DART
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!,
  );
}
TEXT
> 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

DART
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))),
  );
}
TEXT
> 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

Q What's the difference between ColorScheme.fromSeed and manual definition?
A fromSeed auto-generates a complete harmonious palette (12 colors); manual definition is more flexible but you must ensure harmony yourself. Recommend fromSeed as a starting point, then fine-tune.
Q Does Theme.of(context) have a performance cost?
A Yes, each call triggers a rebuild. Cache it outside build: final theme = Theme.of(context);, then reuse the theme variable.
Q How to override the global theme for a component?
A Wrap the subtree that needs overriding with Theme(data: Theme.of(context).copyWith(...), child: widget).
Q How to handle image/icon colors in dark mode?
A Use ColorScheme role colors (like onSurface), avoid hard-coded colors. Use colorFilter for SVG icon tinting.
Q What does ThemeExtension's lerp method do?
A lerp implements interpolation animation during theme switching — Light→Dark transitions smoothly instead of jumping.
Q How to make third-party package components follow custom themes?
A Most Material packages automatically follow ThemeData. Non-Material components need manual theme parameter passing.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Use ColorScheme.fromSeed to create a brand color theme and apply it to MaterialApp.
  2. Intermediate (Difficulty ⭐⭐): Implement Light/Dark/System three-mode switching using Riverpod + SharedPreferences persistence.
  3. Challenge (Difficulty ⭐⭐⭐): Create a complete ShopApp theme system: BrandTokens extension + Light/Dark dual themes + large-text accessibility mode + component-level theme overrides.

← Previous Lesson | Next Lesson →

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏