Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

flutter-bloc

/flutter-bloc

Zarządza stanem Flutter przez Bloc i Cubit: zdarzenia, stany, transformery i testy z bloc_test.

Licencja
MIT
Ostatnia zmiana repozytorium
05.11.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 05.11.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Zarządza stanem Flutter przez Bloc i Cubit: zdarzenia, stany, transformery i testy z bloc_test.

Oryginalny opis (EN)

Bloc and Cubit state management with flutter_bloc — Cubit vs Bloc, events and states as sealed classes, emit and on<Event> handlers, event transformers (droppable, restartable, sequential, debounce via bloc_concurrency), BlocProvider/MultiBlocProvider, RepositoryProvider, BlocBuilder with buildWhen, BlocSelector, BlocListener and BlocConsumer for side effects, context.read/watch/select, BlocObserver, hydrated_bloc, and testing with bloc_test (blocTest, MockBloc). Use when the project imports bloc or flutter_bloc, or when writing, reviewing, or testing Blocs/Cubits.

Jak działa

  1. Cubit or Bloc
  2. States and events
  3. Bloc with a transformer
  4. Providing and consuming
  5. Rules
  6. Testing
Sekcje z nagłówków SKILL.md, w oryginale · 130 linii, 713 słów
Podgląd SKILL.md
---
name: flutter-bloc
description: "Bloc and Cubit state management with flutter_bloc — Cubit vs Bloc, events and states as sealed classes, emit and on<Event> handlers, event transformers (droppable, restartable, sequential, debounce via bloc_concurrency), BlocProvider/MultiBlocProvider, RepositoryProvider, BlocBuilder with buildWhen, BlocSelector, BlocListener and BlocConsumer for side effects, context.read/watch/select, BlocObserver, hydrated_bloc, and testing with bloc_test (blocTest, MockBloc). Use when the project imports bloc or flutter_bloc, or when writing, reviewing, or testing Blocs/Cubits."
license: MIT
metadata:
  author: Matiss Kalnins
  version: "0.5.0"
---

**Persona:** You keep Blocs predictable: immutable states, sealed events, one Bloc per feature concern, and no UI code inside them.

## Cubit or Bloc

- **Cubit**: methods call `emit(newState)`. Use it for simple state with direct actions (toggles, forms, simple fetches).
- **Bloc**: `add(Event)` → handlers → `emit`. Use it when you need event transformers (debounce search, drop duplicate taps), an event-level audit trail, or complex flows.
- Start with a Cubit, and promote it to a Bloc when you need event transformers or traceability.

## States and events

```dart
sealed class SearchEvent {}
final class QueryChanged extends SearchEvent { QueryChanged(this.query); final String query; }
final class Cleared extends SearchEvent {}

sealed class SearchState extends Equatable {
  const SearchState();
  @override
  List<Object?> get props => [];
}
final class SearchIdle extends SearchState { const SearchIdle(); }
final class SearchLoading extends SearchState { const SearchLoading(); }
final class SearchSuccess extends SearchState {
  const SearchSuccess(this.results);
  final IList<SearchHit> results;   // IList: final alone wouldn't stop mutation of a List
  @override
  List<Object?> get props => [results];
}
final class SearchFailure extends SearchState {
  const SearchFailure(this.failure);
  final AppFailure failure;
  @override
  List<Object?> get props => [failure];
}
```

States are deeply immutable and need value equality (equatable or freezed). Every field is `final`, and collections are `IList`/`ISet`/`IMap` from `fast_immutable_collections`. Prefer freezed primary-constructor classes for states (see `dart-json-serialization`); hand-written `Equatable` states like the one above are fine too. Bloc skips emitting a state equal to the current one, so mutating a list inside the current state and re-emitting it silently does nothing. Always emit a new instance.

## Bloc with a transformer

```dart
class SearchBloc extends Bloc<SearchEvent, SearchState> {
  SearchBloc(this._repo) : super(const SearchIdle()) {
    on<QueryChanged>(
      _onQuery,
      // debounce (stream_transform), then cancel the previous search (bloc_concurrency)
      transformer: (events, mapper) => restartable<QueryChanged>().call(events.debounce(const Duration(milliseconds: 300)), mapper),
    );
    on<Cleared>((_, emit) => emit(const SearchIdle()));
  }
  final SearchRepository _repo;

  Future<void> _onQuery(QueryChanged e, Emitter<SearchState> emit) async {
    if (e.query.isEmpty) return emit(const SearchIdle());
    emit(const SearchLoading());
    emit(switch (await _repo.search(e.query)) {   // repositories return Result (see dart-error-handling)
      Ok(:final value) => SearchSuccess(value),
      Err(:final failure) => SearchFailure(failure),
    });
  }
}
```

- Transformers come from `bloc_concurrency`: `sequential()`, `concurrent()` (default), `droppable()` (ignore taps while busy), `restartable()` (cancel the previous one, which is ideal for search).
- For streams, use `await emit.forEach(stream, onData: (d) => State(d))` inside a handler, rather than listening manually.
- Never call `emit` after the handler has completed (for example from a stray `.then`). Bloc throws.

## Providing and consuming

```dart
MultiRepositoryProvider(
  providers: [RepositoryProvider(create: (_) => SearchRepository(api))],
  child: BlocProvider(
    create: (context) => SearchBloc(context.read<SearchRepository>()),
    child: const SearchPage(),
  ),
);

// Rebuild UI
BlocBuilder<SearchBloc, SearchState>(
  builder: (context, state) => switch (state) {
    SearchIdle() => const Hint(),
    SearchLoading() => const LinearProgressIndicator(),
    SearchSuccess(:final results) => SearchHitList(results),
    SearchFailure(:final failure) => ErrorText(failure.userMessage),
  },
);

// Side effects only
BlocListener<AuthBloc, AuthState>(
  listenWhen: (prev, curr) => prev.runtimeType != curr.runtimeType,
  listener: (context, state) {
    if (state case Unauthenticated()) context.go("/login");
  },
  child: ...,
);

// A slice
final int count = context.select((CartBloc b) => b.state.items.length);
```

- `BlocProvider(create:)` closes the bloc automatically. `BlocProvider.value(value:)` doesn't, so use it only to pass an existing bloc to a new route.
- Dispatch with `context.read<SearchBloc>().add(QueryChanged(q))` in callbacks. Never use `context.watch` in callbacks.
- Navigation, snackbars, and dialogs go in `BlocListener`, never in `BlocBuilder`.

## Rules

- Blocs don't import `package:flutter/material.dart` and never take a `BuildContext`.
- A Bloc has no mutable fields other than its state. Anything that changes over time is part of the state.
- Lift UI state into Cubits/Blocs too (selected tab, filters, expanded rows, form drafts), provided at the route. Widgets stay stateless, except for controller leaves that mirror bloc state.
- Self-connected components (`BlocBuilder`, `BlocSelector`, `context.select`) watch blocs. Rows and sections get plain values and callbacks (see `flutter-widgets`).
- Blocs depend on repositories (constructor-injected), not on other blocs. If one feature reacts to another, subscribe to the other feature's repository stream, or coordinate in the UI with a `BlocListener`.
- Add a `BlocObserver` (`Bloc.observer = AppBlocObserver();`) to log transitions and errors in debug builds.
- To persist state across launches, use `hydrated_bloc`'s `HydratedBloc` with `fromJson`/`toJson`.

## Testing

```dart
blocTest<SearchBloc, SearchState>(
  "emits loading then success",
  build: () => SearchBloc(FakeSearchRepository(hits: IList([hit1]))),
  act: (bloc) => bloc.add(QueryChanged("flutter")),
  wait: const Duration(milliseconds: 300),   // debounce
  expect: () => [const SearchLoading(), SearchSuccess(IList([hit1]))],
);
```

In widget tests, use `MockBloc` (from `bloc_test`) with `whenListen` to drive UI states.

Wersje

RepozytoriumWynikLicencja
Ta strona · Dee9975/cc-skills-flutter100MIT
dhruvanbhalara/skills100MIT

Migawka bazy z 13.11.2026 · wersja paczki 6263cf02eed7 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100bloc
    Podaje dobre praktyki zarządzania stanem Bloc we Flutter i Dart: Cubit kontra Bloc, nazewnictwo zdarzeń i stanów, klasy sealed z Equatable, podział Page i View oraz BlocBuilder, BlocListener i BlocSelector wraz z testami.
  • 100bloc
    Pomaga tworzyć Cubit i Bloc, modelować stan klasami sealed lub enumami statusu, łączyć BlocBuilder, BlocListener i BlocProvider, pisać testy bloc oraz wybierać między Cubit a Bloc.
  • 100flutter-bloc-state-management
    Wdraża stan, zdarzenia, przejścia i współbieżność asynchroniczną w BLoC i Cubit we Flutterze, w tym zdarzenia z debounce, anulowalne i testy bloc.
  • 100bloc-cubit
    Pomaga w zarządzaniu stanem we Flutterze z Bloc i Cubit: wybór między nimi, współpraca bloc z flutter_bloc, cykl życia, testowanie i bezpieczne ustawienia domyślne.
  • 100clean-arch-ui
    Łączy widżety Fluttera ze stanem Cubit lub Bloc, obsługuje ładowanie i błędy, lokalizację i zdarzenia prezentacji w warstwie UI.
  • 100clean-arch-presentation
    Pisze klasy Cubit i Bloc we Flutterze: stany, zdarzenia, wywołania przypadków użycia, efekty jednorazowe i mapowanie błędów.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.