Flutter Mobile Development · บทเรียน

ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์

กำหนดและใช้งานโทเค็นการออกแบบเฉพาะแบรนด์ด้วยการเขียนคลาส ThemeExtension

บทเรียน 3 จาก 413 ขั้นตอน

ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์ เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Brand Tokens Need a Home

Material 3 gives you a rich ColorScheme, but real products carry extra design decisions that don't map to any built-in slot: a brand gradient, a success color, a promotional accent, a custom card radius.

Hardcoding these as global constants breaks down the moment you support light and dark modes, because a single constant can't change with the active ThemeData.

  • You want these values to live inside the theme.
  • You want them to interpolate smoothly during theme animations.
  • You want to read them with the same Theme.of(context) ergonomics as everything else.

Flutter's answer is ThemeExtension.

What a ThemeExtension Is

ThemeExtension<T> is an abstract class you subclass to attach your own typed bundle of values to a ThemeData.

The generic parameter T is your own class. This is what lets Flutter store and later retrieve your extension by its exact type instead of by a string key.

  • It is type-safe: no casting from a Map.
  • It is theme-aware: it ships inside ThemeData, so light and dark can hold different instances.
  • It supports animation: Flutter calls lerp to blend two instances when themes change.

You must implement two methods: copyWith and lerp.

Declaring the Extension Class

Start by subclassing ThemeExtension with your class as the type argument. Make every field final so instances are immutable.

Here we model a small brand palette: a promotional accent, a success color, and a brand gradient.

import 'package:flutter/material.dart';

class BrandColors extends ThemeExtension<BrandColors> {
  const BrandColors({
    required this.accent,
    required this.success,
    required this.brandGradient,
  });

  final Color accent;
  final Color success;
  final Gradient brandGradient;

  @override
  ThemeExtension<BrandColors> copyWith({
    Color? accent,
    Color? success,
    Gradient? brandGradient,
  }) {
    return BrandColors(
      accent: accent ?? this.accent,
      success: success ?? this.success,
      brandGradient: brandGradient ?? this.brandGradient,
    );
  }
}

Implementing copyWith

copyWith returns a new instance with some fields replaced. The pattern is always the same: each parameter is nullable, and you fall back to this.field when the caller passes null.

  • It keeps the class immutable — you never mutate, you clone with changes.
  • It is what consumers use to tweak a single token without rebuilding the whole object.

Note the return type is ThemeExtension<BrandColors>, matching the abstract signature, even though you construct a concrete BrandColors.

Implementing lerp for Smooth Transitions

lerp (linear interpolation) blends this toward another instance by a factor t between 0.0 and 1.0. Flutter calls it during theme animations so your custom tokens fade as smoothly as the built-in ones.

Use the static helpers each type provides: Color.lerp and Gradient.lerp. Guard against the other being a different extension type by returning this.

@override
ThemeExtension<BrandColors> lerp(
  covariant ThemeExtension<BrandColors>? other,
  double t,
) {
  if (other is! BrandColors) {
    return this;
  }
  return BrandColors(
    accent: Color.lerp(accent, other.accent, t)!,
    success: Color.lerp(success, other.success, t)!,
    brandGradient: Gradient.lerp(brandGradient, other.brandGradient, t)!,
  );
}

Defining Light and Dark Instances

Because the extension lives inside ThemeData, you create one instance tuned for light mode and another for dark mode. Expose them as static const (or static final when a value isn't const-constructible) on the class for easy reference.

This is exactly the win over global constants: the same token name resolves to different values depending on the active theme.

class BrandColors extends ThemeExtension<BrandColors> {
  // ...constructor, fields, copyWith, lerp as before...

  static const light = BrandColors(
    accent: Color(0xFFFF6D00),
    success: Color(0xFF2E7D32),
    brandGradient: LinearGradient(
      colors: [Color(0xFFFF6D00), Color(0xFFFFAB40)],
    ),
  );

  static const dark = BrandColors(
    accent: Color(0xFFFFAB40),
    success: Color(0xFF66BB6A),
    brandGradient: LinearGradient(
      colors: [Color(0xFFFFAB40), Color(0xFFFFD180)],
    ),
  );
}

Registering the Extension on ThemeData

Attach instances through the extensions parameter of ThemeData. It takes an Iterable of extensions; Flutter indexes them by runtime type.

Give your light ThemeData the light instance and your dark ThemeData the dark instance so they switch automatically with the platform brightness.

MaterialApp(
  theme: ThemeData(
    colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
    extensions: const [BrandColors.light],
  ),
  darkTheme: ThemeData(
    colorScheme: ColorScheme.fromSeed(
      seedColor: Colors.deepPurple,
      brightness: Brightness.dark,
    ),
    extensions: const [BrandColors.dark],
  ),
  home: const HomePage(),
);

Consuming the Extension in a Widget

Read your extension with Theme.of(context).extension<BrandColors>(). The generic type argument is the lookup key, returning a nullable BrandColors?.

Once you have the instance, every token is a plain typed field — no casts, full autocomplete.

class PromoBanner extends StatelessWidget {
  const PromoBanner({super.key});

  @override
  Widget build(BuildContext context) {
    final brand = Theme.of(context).extension<BrandColors>()!;
    return Container(
      decoration: BoxDecoration(
        gradient: brand.brandGradient,
        borderRadius: BorderRadius.circular(16),
      ),
      padding: const EdgeInsets.all(16),
      child: Text(
        'Limited offer',
        style: TextStyle(color: brand.accent),
      ),
    );
  }
}

A Clean Consumption Extension

Calling Theme.of(context).extension<BrandColors>()! everywhere is noisy. A common idiom is to add a small BuildContext extension that hides the lookup behind a getter.

  • It centralizes the non-null assertion in one place.
  • Call sites become a tidy context.brand.accent.
extension BrandThemeX on BuildContext {
  BrandColors get brand =>
      Theme.of(this).extension<BrandColors>()!;
}

// Usage inside any build method:
// final color = context.brand.success;

Pure-Dart Mental Model of lerp

You can reason about lerp without Flutter. Interpolation is just a + (b - a) * t applied per channel. The snippet below blends two integers the same way Color.lerp blends each ARGB channel.

Running this shows how t = 0 yields the start, t = 1 yields the end, and t = 0.5 yields the midpoint — the exact behavior your theme animation relies on.

int lerpInt(int a, int b, double t) {
  return (a + (b - a) * t).round();
}

void main() {
  const start = 0; // think: red channel of color A
  const end = 200; // red channel of color B
  for (final t in [0.0, 0.25, 0.5, 0.75, 1.0]) {
    print('t=$t -> ${lerpInt(start, end, t)}');
  }
}

Multiple Extensions and Common Pitfalls

You can register several extensions side by side — for example BrandColors and a separate BrandShapes for radii and spacing. Flutter keys each by its own type, so they never collide.

  • Forgetting to register: extension<BrandColors>() returns null if you never added it to ThemeData.extensions; the ! then throws.
  • Skipping lerp: if lerp just returns this, theme transitions snap instead of fading.
  • Wrong type argument: the type in extension<T>() must match the registered class exactly.
ThemeData(
  extensions: const [
    BrandColors.light,
    BrandShapes.standard,
  ],
);

// Look each one up independently:
// final brand = Theme.of(context).extension<BrandColors>()!;
// final shapes = Theme.of(context).extension<BrandShapes>()!;

Quick Check

You added BrandColors to your light and dark ThemeData and now animate between them. The brand accent color jumps abruptly instead of fading smoothly. Which mistake most likely causes this?

Recap

You now own a full custom theming workflow in Flutter:

  • Subclass ThemeExtension<T> with final fields for your brand tokens.
  • Implement copyWith (nullable params, fall back to this.field) and lerp (use Color.lerp, Gradient.lerp, guard the type).
  • Build distinct light and dark instances and register them via ThemeData.extensions.
  • Consume with Theme.of(context).extension<BrandColors>(), ideally wrapped in a context.brand getter.

The payoff: brand-specific design tokens that are type-safe, mode-aware, and animate smoothly — just like Material 3's built-in ColorScheme.

เริ่มต้นได้ฟรี

เรียนรู้ Dart ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
22
บทเรียน
88

คำถามที่พบบ่อย

บทเรียน “ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์”

กำหนดและใช้งานโทเค็นการออกแบบเฉพาะแบรนด์ด้วยการเขียนคลาส ThemeExtension คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม

ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ชุดสี Material 3 และสีตั้งต้น
  2. สีแบบไดนามิกและธีมสว่าง/มืดแบบปรับตามบริบท
  3. ThemeExtension แบบกำหนดเองสำหรับโทเค็นแบรนด์
  4. ตัวอักษรแบบตอบสนองและธีมขององค์ประกอบ
← กลับไปที่ Flutter Mobile Development