dart-flutter-patterns

dart-flutter-patterns

熱門

適用於正式營運的 Dart 與 Flutter 設計模式,涵蓋 Null Safety、不可變狀態(Immutable State)、非同步組合、Widget 架構、熱門狀態管理框架(BLoC、Riverpod、Provider)、GoRouter 導覽、Dio 網路請求、Freezed 程式碼生成以及 Clean Architecture。

24萬星標
3.6萬分支
更新於 2026/8/11
SKILL.md
唯讀
名稱
dart-flutter-patterns
描述

適用於正式營運的 Dart 與 Flutter 設計模式,涵蓋 Null Safety、不可變狀態(Immutable State)、非同步組合、Widget 架構、熱門狀態管理框架(BLoC、Riverpod、Provider)、GoRouter 導覽、Dio 網路請求、Freezed 程式碼生成以及 Clean Architecture。

Dart/Flutter 設計模式 (Patterns)

何時使用

當您需要以下操作時使用此 Skill:

  • 開始開發新的 Flutter 功能,需要地道的狀態管理、導覽或資料存取模式
  • 審查或撰寫 Dart 程式碼,需要關於 Null Safety、Sealed Types 或非同步組合的指導
  • 建立新的 Flutter 專案,並在 BLoC、Riverpod 或 Provider 之間進行選擇
  • 實作安全的 HTTP 客戶端、WebView 整合或本地儲存
  • 為 Flutter Widget、Cubit 或 Riverpod Provider 撰寫測試
  • 搭配認證守衛(Auth Guards)設定 GoRouter

運作方式

此 Skill 提供可直接複製貼上的 Dart/Flutter 程式碼範例,按關注點(Concern)分類:

  1. Null safety — 避免使用 !,優先使用 ?./??/模式比對(Pattern Matching)
  2. 不可變狀態(Immutable state) — Sealed Classes、freezed、copyWith
  3. 非同步組合 — 並行 Future.wait、在 await 後安全使用 BuildContext
  4. Widget 架構 — 拆分為 Class(而非 Helper 函數/方法)、const 傳播、區域化重繪(Scoped Rebuilds)
  5. 狀態管理 — BLoC/Cubit 事件、Riverpod Notifiers 與衍生 Providers
  6. 導覽 — GoRouter 搭配透過 refreshListenable 實現的響應式認證守衛
  7. 網路請求 — Dio 搭配攔截器(Interceptors),具有單次重試保護的 Token 刷新機制
  8. 錯誤處理 — 全域擷取、ErrorWidget.builder、Crashlytics 整合
  9. 測試 — 單元測試(BLoC test)、Widget 測試(ProviderScope 覆蓋)、優先使用 Fake 而非 Mock

範例

// Sealed 狀態 — 防止不可能出現的狀態組合
sealed class AsyncState<T> {}
final class Loading<T> extends AsyncState<T> {}
final class Success<T> extends AsyncState<T> { final T data; const Success(this.data); }
final class Failure<T> extends AsyncState<T> { final Object error; const Failure(this.error); }

// GoRouter 搭配響應式認證重定向
final router = GoRouter(
  refreshListenable: GoRouterRefreshStream(authCubit.stream),
  redirect: (context, state) {
    final authed = context.read<AuthCubit>().state is AuthAuthenticated;
    if (!authed && !state.matchedLocation.startsWith('/login')) return '/login';
    return null;
  },
  routes: [...],
);

// Riverpod 衍生 Provider 搭配安全的 firstWhereOrNull
@riverpod
double cartTotal(Ref ref) {
  final cart = ref.watch(cartNotifierProvider);
  final products = ref.watch(productsProvider).valueOrNull ?? [];
  return cart.fold(0.0, (total, item) {
    final product = products.firstWhereOrNull((p) => p.id == item.productId);
    return total + (product?.price ?? 0) * item.quantity;
  });
}

適用於 Dart 和 Flutter 應用程式的實用且可在生產環境中使用的模式。盡可能獨立於具體函式庫,並明確涵蓋最常見的生態系統套件。


1. Null Safety 基礎

優先使用模式比對而非 Bang 運算子(!)

// 不佳 — 若為 null 會在執行時期崩潰
final name = user!.name;

// 良好 — 提供預設備用值
final name = user?.name ?? 'Unknown';

// 良好 — Dart 3 模式比對(複雜情況下的首選)
final display = switch (user) {
  User(:final name, :final email) => '$name <$email>',
  null => 'Guest',
};

// 良好 — Guard 提前返回
String getUserName(User? user) {
  if (user == null) return 'Unknown';
  return user.name; // 檢查後自動提升(Promoted)為非 null
}

避免過度使用 late

// 不佳 — 將 null 錯誤推遲到執行時期
late String userId;

// 良好 — 可為空型態並配合明確初始化
String? userId;

// 可接受 — 僅在能確保首次存取前已完成初始化時使用 late
// (例如在 initState() 中、任何 Widget 互動之前)
late final AnimationController _controller;

@override
void initState() {
  super.initState();
  _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
}

2. 不可變狀態 (Immutable State)

用於狀態階層的 Sealed Classes

sealed class UserState {}

final class UserInitial extends UserState {}

final class UserLoading extends UserState {}

final class UserLoaded extends UserState {
  const UserLoaded(this.user);
  final User user;
}

final class UserError extends UserState {
  const UserError(this.message);
  final String message;
}

// 窮舉 switch — 編譯器強制要求處理所有分支
Widget buildFrom(UserState state) => switch (state) {
  UserInitial() => const SizedBox.shrink(),
  UserLoading() => const CircularProgressIndicator(),
  UserLoaded(:final user) => UserCard(user: user),
  UserError(:final message) => ErrorText(message),
};

使用 Freezed 簡化不可變狀態樣板程式碼

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
part 'user.g.dart';

@freezed
class User with _$User {
  const factory User({
    required String id,
    required String name,
    required String email,
    @Default(false) bool isAdmin,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

// 使用方式
final user = User(id: '1', name: 'Alice', email: 'alice@example.com');
final updated = user.copyWith(name: 'Alice Smith'); // 不可變更新
final json = user.toJson();
final fromJson = User.fromJson(json);

3. 非同步組合 (Async Composition)

透過 Future.wait 實作結構化並行處理

Future<DashboardData> loadDashboard(UserRepository users, OrderRepository orders) async {
  // 並行執行 — 不要使用序列 await
  final (userList, orderList) = await (
    users.getAll(),
    orders.getRecent(),
  ).wait; // Dart 3 Record 解構 + Future.wait 擴充功能

  return DashboardData(users: userList, orders: orderList);
}

Stream 設計模式

// Repository 對外暴露用於即時資料的響應式 Stream
Stream<List<Item>> watchCartItems() => _db
    .watchTable('cart_items')
    .map((rows) => rows.map(Item.fromRow).toList());

// 在 Widget 層 — 宣告式,無需手動取消訂閱
StreamBuilder<List<Item>>(
  stream: cartRepository.watchCartItems(),
  builder: (context, snapshot) => switch (snapshot) {
    AsyncSnapshot(connectionState: ConnectionState.waiting) =>
        const CircularProgressIndicator(),
    AsyncSnapshot(:final error?) => ErrorWidget(error.toString()),
    AsyncSnapshot(:final data?) => CartList(items: data),
    _ => const SizedBox.shrink(),
  },
)

Await 之後的 BuildContext

// 至關重要 — 在 StatefulWidget 中的任何 await 之後務必檢查 mounted
Future<void> _handleSubmit() async {
  setState(() => _isLoading = true);
  try {
    await authService.login(_email, _password);
    if (!mounted) return; // ← 使用 context 前的保護檢查
    context.go('/home');
  } on AuthException catch (e) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));
  } finally {
    if (mounted) setState(() => _isLoading = false);
  }
}

4. Widget 架構

拆分為 Class,而非私有方法

// 不佳 — 返回 Widget 的私有方法,阻礙了渲染優化
Widget _buildHeader() {
  return Container(
    padding: const EdgeInsets.all(16),
    child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
  );
}

// 良好 — 獨立的 Widget Class,支援 const 與 Element 複用
class _PageHeader extends StatelessWidget {
  const _PageHeader(this.title);
  final String title;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
    );
  }
}

const 傳播

// 不佳 — 每次重繪都會建立新實例
child: Padding(
  padding: EdgeInsets.all(16.0),       // 非 const
  child: Icon(Icons.home, size: 24.0), // 非 const
)

// 良好 — const 阻斷重繪傳播
child: const Padding(
  padding: EdgeInsets.all(16.0),
  child: Icon(Icons.home, size: 24.0),
)

區域化重繪 (Scoped Rebuilds)

// 不佳 — 每次計數變更時整個頁面都會重繪
class CounterPage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider); // 導致整個元件重繪
    return Scaffold(
      body: Column(children: [
        const ExpensiveHeader(), // 被不必要地重繪
        Text('$count'),
        const ExpensiveFooter(), // 被不必要地重繪
      ]),
    );
  }
}

// 良好 — 隔離會重繪的部分
class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(children: [
        ExpensiveHeader(),        // 從不重繪 (const)
        _CounterDisplay(),        // 只有此元件會重繪
        ExpensiveFooter(),        // 從不重繪 (const)
      ]),
    );
  }
}

class _CounterDisplay extends ConsumerWidget {
  const _CounterDisplay();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);
    return Text('$count');
  }
}

5. 狀態管理:BLoC/Cubit

// Cubit — 同步或簡單的非同步狀態
class AuthCubit extends Cubit<AuthState> {
  AuthCubit(this._authService) : super(const AuthState.initial());
  final AuthService _authService;

  Future<void> login(String email, String password) async {
    emit(const AuthState.loading());
    try {
      final user = await _authService.login(email, password);
      emit(AuthState.authenticated(user));
    } on AuthException catch (e) {
      emit(AuthState.error(e.message));
    }
  }

  void logout() {
    _authService.logout();
    emit(const AuthState.initial());
  }
}

// 在 Widget 中使用
BlocBuilder<AuthCubit, AuthState>(
  builder: (context, state) => switch (state) {
    AuthInitial() => const LoginForm(),
    AuthLoading() => const CircularProgressIndicator(),
    AuthAuthenticated(:final user) => HomePage(user: user),
    AuthError(:final message) => ErrorView(message: message),
  },
)

6. 狀態管理:Riverpod

// 自動釋放的非同步 Provider
@riverpod
Future<List<Product>> products(Ref ref) async {
  final repo = ref.watch(productRepositoryProvider);
  return repo.getAll();
}

// 包含複雜變更邏輯的 Notifier
@riverpod
class CartNotifier extends _$CartNotifier {
  @override
  List<CartItem> build() => [];

  void add(Product product) {
    final existing = state.where((i) => i.productId == product.id).firstOrNull;
    if (existing != null) {
      state = [
        for (final item in state)
          if (item.productId == product.id) item.copyWith(quantity: item.quantity + 1)
          else item,
      ];
    } else {
      state = [...state, CartItem(productId: product.id, quantity: 1)];
    }
  }

  void remove(String productId) =>
      state = state.where((i) => i.productId != productId).toList();

  void clear() => state = [];
}

// 衍生 Provider (Selector 模式)
@riverpod
int cartCount(Ref ref) => ref.watch(cartNotifierProvider).length;

@riverpod
double cartTotal(Ref ref) {
  final cart = ref.watch(cartNotifierProvider);
  final products = ref.watch(productsProvider).valueOrNull ?? [];
  return cart.fold(0.0, (total, item) {
    // firstWhereOrNull(來自 collection 套件)可在找不到商品時避免拋出 StateError
    final product = products.firstWhereOrNull((p) => p.id == item.productId);
    return total + (product?.price ?? 0) * item.quantity;
  });
}

7. 使用 GoRouter 進行導覽

final router = GoRouter(
  initialLocation: '/',
  // 當驗證狀態發生變化時,refreshListenable 會重新計算 redirect
  refreshListenable: GoRouterRefreshStream(authCubit.stream),
  redirect: (context, state) {
    final isLoggedIn = context.read<AuthCubit>().state is AuthAuthenticated;
    final isGoingToLogin = state.matchedLocation == '/login';
    if (!isLoggedIn && !isGoingToLogin) return '/login';
    if (isLoggedIn && isGoingToLogin) return '/';
    return null;
  },
  routes: [
    GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
    ShellRoute(
      builder: (context, state, child) => AppShell(child: child),
      routes: [
        GoRoute(path: '/', builder: (_, __) => const HomePage()),
        GoRoute(
          path: '/products/:id',
          builder: (context, state) =>
              ProductDetailPage(id: state.pathParameters['id']!),
        ),
      ],
    ),
  ],
);

8. 使用 Dio 進行 HTTP 請求

final dio = Dio(BaseOptions(
  baseUrl: const String.fromEnvironment('API_URL'),
  connectTimeout: const Duration(seconds: 10),
  receiveTimeout: const Duration(seconds: 30),
  headers: {'Content-Type': 'application/json'},
));

// 新增身份驗證攔截器
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) async {
    final token = await secureStorage.read(key: 'auth_token');
    if (token != null) options.headers['Authorization'] = 'Bearer $token';
    handler.next(options);
  },
  onError: (error, handler) async {
    // 防止無限重試迴圈:每個請求僅嘗試刷新一次
    final isRetry = error.requestOptions.extra['_isRetry'] == true;
    if (!isRetry && error.response?.statusCode == 401) {
      final refreshed = await attemptTokenRefresh();
      if (refreshed) {
        error.requestOptions.extra['_isRetry'] = true;
        return handler.resolve(await dio.fetch(error.requestOptions));
      }
    }
    handler.next(error);
  },
));

// 使用 Dio 的 Repository
class UserApiDataSource {
  const UserApiDataSource(this._dio);
  final Dio _dio;

  Future<User> getById(String id) async {
    final response = await _dio.get<Map<String, dynamic>>('/users/$id');
    return User.fromJson(response.data!);
  }
}

9. 錯誤處理架構

// 全域錯誤擷取 — 在 main() 中設定
void main() {
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    crashlytics.recordFlutterFatalError(details);
  };

  PlatformDispatcher.instance.onError = (error, stack) {
    crashlytics.recordError(error, stack, fatal: true);
    return true;
  };

  runApp(const App());
}

// 用於正式營運環境的自訂 ErrorWidget
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ErrorWidget.builder = (details) => ProductionErrorWidget(details);
    return MaterialApp.router(routerConfig: router);
  }
}

10. 測試速查指南

// 單元測試 — Use Case
test('GetUserUseCase returns null for missing user', () async {
  final repo = FakeUserRepository();
  final useCase = GetUserUseCase(repo);
  expect(await useCase('missing-id'), isNull);
});

// BLoC 測試
blocTest<AuthCubit, AuthState>(
  'emits loading then error on failed login',
  build: () => AuthCubit(FakeAuthService(throwsOn: 'login')),
  act: (cubit) => cubit.login('user@test.com', 'wrong'),
  expect: () => [const AuthState.loading(), isA<AuthError>()],
);

// Widget 測試
testWidgets('CartBadge shows item count', (tester) async {
  await tester.pumpWidget(
    ProviderScope(
      overrides: [cartNotifierProvider.overrideWith(() => FakeCartNotifier(count: 3))],
      child: const MaterialApp(home: CartBadge()),
    ),
  );
  expect(find.text('3'), findsOneWidget);
});

參考資源