Flutter: テーマとスタイリングシステム

テーマはアプリの衣装 — 統一されたスタイルでユーザーは一目でブランドを認識できます。

📋 前提条件: 以下に既に慣れている必要があります

1. このレッスンで学ぶこと


2. ブランド混乱のリアルなストーリー

(1) 悩み:百ページに百の青

BobのShopAppは3人の開発者で開発されており、それぞれが独自の色を定義:Colors.blueColor(0xFF2196F3)Color(0xFF1976D2)。100ページに12種類の異なる青があり、ボタンの角丸は4px、8px、12pxとバラバラ。ダークモードはさらにカオス — 暗い背景にColors.whiteのテキストを使う人もいれば、Colors.grey[300]を使う人もいます。ブランド認識はほぼ存在しません。

(2) ThemeDataソリューション

ThemeDataはすべての色、フォント、シェイプを統一的に定義 — コンポーネントは自動的にテーマからスタイルを導出し、1つの変更がグローバルに反映されます。

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

(3) 成果:ブランド統一 + グローバル切り替え

BobがShopAppブランドテーマを定義した後、すべてのページが自動的に統一スタイルを共有しました。ダークモードはThemeDataの切り替えだけで済み — ページごとの変更は不要でした。


3. ThemeData設定システム

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

(1) ColorSchemeカラーシステム

カラーロール 用途
primary プライマリブランドカラー(ボタン/タブ) #0066CC
onPrimary プライマリカラー上のテキスト #FFFFFF
secondary アクセントカラー #FF6B35
surface カード/背景 #FFFFFF/#1C1C1E
onSurface サーフェス上のテキスト #1C1C1E/#FFFFFF
error エラーカラー #B3261E
outline ボーダー/区切り線 #79747E

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:ShopAppブランドカラー定義

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

4. ThemeDataフル設定

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:ShopApp完全テーマ

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

5. 動的テーマ切り替え

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:Riverpodテーマ管理

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:テーマ切り替え設定ページ

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

6. ThemeExtensionカスタム拡張

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:ブランドトークン拡張

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

7. アクセシビリティ大きなテキストモード

▶ サンプル

TEXT
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

:レスポンシブテキストスケーリング

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

8. 完全な例:ShopAppテーマシステム

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
> 出力: ローカルのFlutter SDKで実行してください(Flutter 3.x / Dart 3.x)。PistonサーバーにはFlutterがインストールされていません — 手元のマシンで`flutter run`して動作確認してください。実際のUI/状態はプラットフォームにより多少異なる場合があります。

❓ よくある質問

Q ColorScheme.fromSeedと手動定義の違いは何ですか?
A fromSeedは調和のとれた完全なパレット(12色)を自動生成します。手動定義はより柔軟ですが、調和を自分で確保する必要があります。fromSeedを開始点として、その後微調整することを推奨します。
Q Theme.of(context)にパフォーマンスコストはありますか?
A はい、毎回リビルドがトリガーされます。buildの外でキャッシュしてください:final theme = Theme.of(context); その後、テーマ変数を再利用します。
Q コンポーネントのグローバルテーマをどうオーバーライドしますか?
A オーバーライドが必要なサブツリーを Theme(data: Theme.of(context).copyWith(...), child: widget) でラップします。
Q ダークモードで画像/アイコンの色はどう処理しますか?
A ColorSchemeロールカラー(onSurfaceなど)を使用し、ハードコードされた色を避けてください。SVGアイコンの色付けにはcolorFilterを使用します。
Q ThemeExtensionのlerpメソッドは何をするものですか?
A lerpはテーマ切り替え時の補間アニメーションを実装します — Light→Darkの移行がジャンプではなくスムーズに行われます。
Q サードパーティパッケージのコンポーネントをカスタムテーマに追従させるには?
A ほとんどのMaterialパッケージは自動的にThemeDataに追従します。非Materialコンポーネントは手動でテーマパラメータを渡す必要があります。

📖 まとめ


📝 練習問題

  1. 基本 (⭐):ColorScheme.fromSeedを使ってブランドカラーテーマを作成し、MaterialAppに適用してください。
  2. 中級 (⭐⭐):Riverpod + SharedPreferences永続化を使ってライト/ダーク/システム3モード切り替えを実装してください。
  3. チャレンジ (⭐⭐⭐):完全なShopAppテーマシステムを作成してください:BrandTokens拡張 + ライト/ダークデュアルテーマ + 大きなテキストアクセシビリティモード + コンポーネントレベルのテーマオーバーライド。

← 前のレッスン | 次のレッスン →

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%