移动端安装
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- 工程开发
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 中等消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 底层运行要求
- 无特殊要求
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: flutter-bloc-feature-pattern
description: Use when adding a new feature to a Bloc-based Flutter project (after `flutter-bloc-setup`), stru…
category: 工程开发
runtime: 无特殊运行时
---
# flutter-bloc-feature-pattern 输出预览
## PART A: 任务判断
- 适用问题:代码实现、重构、调试或代码审查。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Contents / The Event/State/Bloc trio / Sealed states with freezed”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于代码实现、重构、调试或代码审查,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Contents / The Event/State/Bloc trio / Sealed states with freezed”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、会按任务需要访问外部网络、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件;会按任务需要访问外部网络;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件。
先用一个小任务确认它会围绕“Contents / The Event/State/Bloc trio / Sealed states with freezed”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: flutter-bloc-feature-pattern
description: Use when adding a new feature to a Bloc-based Flutter project (after `flutter-bloc-setup`), stru…
category: 工程开发
source: tomevault-io/skills-registry
---
# flutter-bloc-feature-pattern
## 什么时候使用
- 把工程方向的常用动作沉淀成 Agent 可调用的技能 适合处理工程开发场景下的代码实现、调试、重构、测试或代码审查,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代…
- 面向代码实现、重构、调试或代码审查,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Contents / The Event/State/Bloc trio / Sealed states with freezed」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件;会按任务需要访问外部网络;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "flutter-bloc-feature-pattern" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Contents / The Event/State/Bloc trio / Sealed states with freezed
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> 无特殊运行时 | 读取文件、写入/修改文件 | 会按任务需要访问外部网络
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Scaffolding a Bloc Feature
Defines the canonical shape of a Bloc-driven feature: three files (<feature>_event.dart, <feature>_state.dart, <feature>_bloc.dart), sealed states with freezed, and an explicit EventTransformer per handler. Every other skill in the family (flutter-bloc-async-api, flutter-bloc-stream-tracking, flutter-bloc-testing, flutter-bloc-forms) builds on this shape. Prerequisite: flutter-bloc-setup.
Contents
- The Event/State/Bloc trio
- Sealed states with freezed
- Event handlers and concurrency
- Wiring the View
- Persistence (optional)
- Workflow: Scaffold a new feature
- Applied to Talabat-clone
- Examples
The Event/State/Bloc trio
Every feature has exactly three files under lib/ui/features/<feature>/bloc/.
| File | Responsibility | Contains |
|---|---|---|
<feature>_event.dart |
User intent and side-effect triggers. Plain data. | Sealed <Feature>Event class with one variant per intent. |
<feature>_state.dart |
Immutable UI snapshots. Plain data. | Sealed <Feature>State class with one variant per render mode. |
<feature>_bloc.dart |
Maps events to states. The only place that calls repositories. | class <Feature>Bloc extends Bloc<<Feature>Event, <Feature>State> (or HydratedBloc if persisting). |
Events and states are never mutable. The Bloc constructor registers handlers via on<Event>(handler, transformer: ...) and emits new state instances. Views observe state and dispatch events; they never read fields off the Bloc directly.
Sealed states with freezed
Use @freezed with a sealed class so a switch over state variants is exhaustive at compile time. Forgetting to handle a variant becomes a compile error rather than a runtime UI bug.
// lib/ui/features/cart/bloc/cart_state.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:my_app/domain/models/cart_item.dart';
import 'package:my_app/domain/models/money.dart';
part 'cart_state.freezed.dart';
part 'cart_state.g.dart'; // required when the state is also `HydratedBloc`-persisted
@Freezed(unionKey: 'type') // stable discriminator key across class renames
sealed class CartState with _$CartState {
const factory CartState.initial() = CartInitial;
const factory CartState.loading() = CartLoading;
const factory CartState.loaded({
required List<CartItem> items,
required Money subtotal,
required Money total,
}) = CartLoaded;
const factory CartState.failure({required String message}) = CartFailure;
// Required for `HydratedBloc` round-trip — `fromJson` is **not** generated
// automatically; you must declare this factory yourself. `CartItem` and
// `Money` must each be JSON-serializable (typically also `@freezed` classes).
factory CartState.fromJson(Map<String, dynamic> json) =>
_$CartStateFromJson(json);
}
The View consumes the sealed state with a Dart 3 pattern switch:
final widget = switch (state) {
CartInitial() => const _EmptyCart(),
CartLoading() => const Center(child: CircularProgressIndicator()),
CartLoaded(:final items, :final total) => _CartList(items: items, total: total),
CartFailure(:final message) => _ErrorBanner(message: message),
};
If a future PR adds a CartLoaded.suspended variant, every switch in the codebase fails to compile until handled. That is the point.
Event handlers and concurrency
bloc_concurrency provides four EventTransformers. Pick the one that matches the semantic of the event, not the one that "feels safe".
| Transformer | Use when | Example event |
|---|---|---|
droppable() |
Submit-once. Ignore further taps while one is in flight. | OrderPlaced, PaymentSubmitted |
restartable() |
Only the latest matters. Cancel the in-flight handler when a new event arrives. | SearchQueryChanged, RefreshRequested |
sequential() |
Order matters. Run handlers one at a time, FIFO. | CartItemAdded, CartItemQtyChanged |
concurrent() (default) |
Independent fetches. Run in parallel. | ProductDetailsLoaded, ReviewsLoaded |
class CartBloc extends HydratedBloc<CartEvent, CartState> {
CartBloc({required CartRepository repo})
: _repo = repo,
super(const CartState.initial()) {
on<CartItemAdded>(_onItemAdded, transformer: sequential());
on<CartItemQtyChanged>(_onQtyChanged, transformer: sequential());
on<CartCleared>(_onCleared, transformer: droppable());
}
final CartRepository _repo;
// ...handlers
}
Sequential is not the default. The default concurrent() will reorder cart mutations — adding then removing the same item could leave the item in the cart if the remove handler finishes first. Always state the transformer explicitly for any handler that mutates shared state.
Wiring the View
Four widgets bridge a Bloc to the widget tree. Pick the narrowest one that does the job.
| Widget | Purpose | Rebuilds? |
|---|---|---|
BlocProvider |
Inject a Bloc into the subtree. Place at the route, not at app root. | n/a |
BlocBuilder<B, S> |
Rebuild on every state change. The default. | yes, on every state |
BlocSelector<B, S, T> |
Rebuild only when a derived value T changes. Use for fine-grained updates. |
yes, only when selector output changes |
BlocListener<B, S> |
Fire-and-forget side effects: snackbar, navigation, dialog. | no — child is unaffected |
BlocConsumer |
Rare combination of builder + listener. | yes |
Common mistake: wrapping the entire screen in a BlocBuilder that rebuilds 30 widgets when only the cart total changed. Use BlocSelector for the total and let the rest of the tree stay stable.
Persistence (optional)
For state that must survive a cold start (cart, auth tokens, recently-viewed list), extend HydratedBloc<E, S> instead of Bloc<E, S> — or add HydratedMixin to an existing Cubit/Bloc and call hydrate() in its constructor when changing the parent class isn't an option. Override fromJson and toJson on the Bloc. With freezed, the serialization helpers are generated — but only when the state declares an explicit factory State.fromJson(...) factory and the file declares part 'state.g.dart';. See the CartState snippet above; missing either of these makes _$CartStateFromJson undefined and the file won't compile.
Always override storagePrefix to a stable string literal:
@override
String get storagePrefix => 'CartBloc';
The default storage key is runtimeType.toString(), which gets mangled by Dart's minifier in flutter build apk --release / --obfuscate. A user upgrading the app would find their persisted cart unreadable because the storage key changed names between builds. Pin the prefix in source so the key survives minification.
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
class CartBloc extends HydratedBloc<CartEvent, CartState> {
CartBloc({required CartRepository repo})
: _repo = repo,
super(const CartState.initial()) {
// Persistence and transformers coexist — the example is deliberately
// explicit about both so readers see them together.
on<CartHydrated>(_onHydrated, transformer: droppable());
on<CartItemAdded>(_onItemAdded, transformer: sequential());
on<CartItemQtyChanged>(_onQtyChanged, transformer: sequential());
on<CartCleared>(_onCleared, transformer: droppable());
}
final CartRepository _repo;
// ...handlers (omitted; each emits state.copyWith(...) per business rule)
// Pin the storage key so release builds (which may minify class names)
// continue reading the same persisted state across upgrades.
@override
String get storagePrefix => 'CartBloc';
@override
CartState? fromJson(Map<String, dynamic> json) => CartState.fromJson(json);
@override
Map<String, dynamic>? toJson(CartState state) =>
(state as dynamic).toJson() as Map<String, dynamic>?;
}
toJson is cast through dynamic because freezed's generated toJson lives on each variant (e.g. CartLoaded.toJson()), not on the sealed parent's static analysis surface. The runtime resolution picks the right variant; the cast just gets past static type checking.
Limitations
Persisting a Bloc whose handler uses restartable() or concurrent() has two distinct ordering subtleties — don't conflate them:
restartable()and in-flight emits. When event B arrives during event A's handler,restartable()marks A's emitter as done. Anyemit(...)A tries after that is silently dropped (good). The persisted state reflects whatever was emitted before B took over — so persistence sees the last successful emit, not necessarily the last dispatched event.- Process death, separately. If the app is killed while A is mid-
await, A never gets the chance to emit at all — there's no "cancellation" because there's no process. The persisted state is whatever was emitted before A started.
Either way: treat persisted state as a starting point. When the screen mounts after a cold start, re-fetch from the API rather than assuming the persisted state reflects an in-flight request's eventual result.
Workflow: Scaffold a new feature
Task Progress
- Step 1 — Pick a feature name. Lowercase, singular noun (e.g.,
cart,auth,restaurant_list). - Step 2 — Create the directory.
mkdir -p lib/ui/features/<feature>/{bloc,view}. - Step 3 — Write
<feature>_event.dart. Sealed<Feature>Eventclass with one factory per user intent. No logic. - Step 4 — Write
<feature>_state.dart. Sealed<Feature>StatewithInitial,Loading,Loaded(...),Failure(message)at minimum. Add domain-specific variants as needed. - Step 5 — Write
<feature>_bloc.dart. ExtendBloc<E, S>(orHydratedBloc<E, S>if persisting). Inject the repository via constructor. - Step 6 — Register handlers with explicit transformers. Use
sequential()for mutations,restartable()for queries,droppable()for submits,concurrent()only for independent fetches. - Step 7 — If persisting. Override
fromJson/toJsonon the Bloc usingfreezed-generated helpers. - Step 8 — Generate code.
dart run build_runner build --delete-conflicting-outputs(or rely on thewatch -dside terminal fromflutter-bloc-setup). - Step 9 — Wire the View. Wrap the route in
BlocProvider(create: (_) => <Feature>Bloc(repo: context.read<<Feature>Repository>())). UseBlocBuilderfor rendering,BlocListenerfor side effects,BlocSelectorfor fine-grained rebuilds. - Step 10 — Feedback loop. Run
flutter analyze→ review compile errors → if aswitchover state is non-exhaustive, handle the missing variant → re-run.
Applied to Talabat-clone
The cart in this app has the most rules-heavy state in the system: one-cart / one-store / one-city, persistence across cold starts, and a "switch store" guard (PRD_catalog.md §15.5, PRD_states.md §7).
// pseudocode sketch — see the Counter example below for runnable form
// CartEvent
sealed class CartEvent
CartHydrated() // app startup, deserialize from disk
CartItemAdded(Product product, int qty) // user taps "+" on a product card
CartItemQtyChanged(String itemId, int qty) // bottom-sheet qty stepper
CartItemRemoved(String itemId) // swipe-to-delete
CartCleared() // checkout success or explicit clear
CartStoreSwitchRequested(Product fromOtherStore) // user added from a different store
CartStoreSwitchConfirmed() // user confirmed "discard current cart"
CartStoreSwitchCancelled() // user backed out
// CartState
sealed class CartState
CartInitial()
CartLoaded(items, store, subtotal, discount, total)
CartStoreSwitchPending(currentLoaded, pendingProduct) // PRD_catalog.md §15.5
CartFailure(message)
CartBloc extends HydratedBloc because the cart must survive cold start. CartItemAdded uses sequential() so two rapid taps on "+" never interleave with CartItemQtyChanged. CartStoreSwitchRequested is a pure state transition — no API call — that puts the Bloc in CartStoreSwitchPending until the user confirms or cancels. CartCleared happens at checkout success when the API confirms Cart: active → converted (PRD_states.md §7).
StoreListBloc does not extend HydratedBloc — store availability depends on operational gating (PRD_states.md §4) and must be re-fetched on launch.
Examples
A complete Counter feature illustrates the trio with no async dependencies. It uses sequential() because increment-then-decrement order matters.
lib/ui/features/counter/bloc/counter_event.dart
import 'package:freezed_annotation/freezed_annotation.dart';
part 'counter_event.freezed.dart';
@freezed
sealed class CounterEvent with _$CounterEvent {
const factory CounterEvent.incremented() = CounterIncremented;
const factory CounterEvent.decremented() = CounterDecremented;
const factory CounterEvent.reset() = CounterReset;
}
lib/ui/features/counter/bloc/counter_state.dart
import 'package:freezed_annotation/freezed_annotation.dart';
part 'counter_state.freezed.dart';
// We use `sealed` uniformly across the codebase, even for one-variant states.
// `abstract` would also compile here but the family standardizes on `sealed`
// so future variants don't trigger a class-shape change.
@freezed
sealed class CounterState with _$CounterState {
const factory CounterState({required int value}) = _CounterState;
}
lib/ui/features/counter/bloc/counter_bloc.dart
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(const CounterState(value: 0)) {
on<CounterIncremented>(
(e, emit) => emit(CounterState(value: state.value + 1)),
transformer: sequential(),
);
on<CounterDecremented>(
(e, emit) => emit(CounterState(value: state.value - 1)),
transformer: sequential(),
);
on<CounterReset>(
(e, emit) => emit(const CounterState(value: 0)),
transformer: droppable(),
);
}
}
lib/ui/features/counter/view/counter_view.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/counter_bloc.dart';
import '../bloc/counter_event.dart';
import '../bloc/counter_state.dart';
class CounterView extends StatelessWidget {
const CounterView({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterBloc(),
child: const _CounterScaffold(),
);
}
}
class _CounterScaffold extends StatelessWidget {
const _CounterScaffold();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: BlocSelector<CounterBloc, CounterState, int>(
selector: (state) => state.value,
builder: (context, value) => Text(
'$value',
style: Theme.of(context).textTheme.displayLarge,
),
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
heroTag: 'inc',
onPressed: () =>
context.read<CounterBloc>().add(const CounterEvent.incremented()),
child: const Icon(Icons.add),
),
const SizedBox(height: 8),
FloatingActionButton(
heroTag: 'dec',
onPressed: () =>
context.read<CounterBloc>().add(const CounterEvent.decremented()),
child: const Icon(Icons.remove),
),
],
),
);
}
}
BlocSelector<CounterBloc, CounterState, int> rebuilds only when state.value changes, not when the Bloc emits a new CounterState instance with the same value. For a single-field state this is overkill, but the pattern matters for screens with many fields where one cell shouldn't trigger a full rebuild.
Source: abdallhMoukdad/flutter-bloc-skills — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核