Wzorzec BLoC ze Streams
Poznaj wzorzec BLoC (Business Logic Component) we Flutterze, aby oddzielić logikę biznesową od interfejsu za pomocą zdarzeń, stanów i strumieni.
Wzorzec BLoC ze Streams to bezpłatna lekcja Flutter Mobile Development na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Flutter Mobile Development, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
What Is BLoC?
BLoC stands for Business Logic Component. It is a pattern that keeps your business logic out of widgets by turning events into states through a stream.
- UI sends events in
- BLoC processes them
- New states flow back out to the UI
Why Another Pattern?
You already know setState, Provider, and Riverpod. BLoC shines when logic is complex and you want:
- Clear separation of UI and logic
- Predictable, testable state transitions
- A reactive stream-based flow
Streams Refresher
A Stream is a sequence of asynchronous values over time. A StreamController lets you push values and expose them as a stream.
final controller = StreamController<int>();
controller.stream.listen((value) => print(value));
controller.add(1);
controller.add(2);Events
An event is an immutable class describing something the user did. Define them as plain Dart classes.
abstract class CounterEvent {}
class Increment extends CounterEvent {}
class Decrement extends CounterEvent {}States
A state is an immutable snapshot of what the UI should show. Keep it simple and serializable.
class CounterState {
final int count;
const CounterState(this.count);
}The Bloc Class
Using the flutter_bloc package, a Bloc maps events to states with on<Event> handlers.
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(const CounterState(0)) {
on<Increment>((e, emit) => emit(CounterState(state.count + 1)));
on<Decrement>((e, emit) => emit(CounterState(state.count - 1)));
}
}Providing the Bloc
Wrap part of the tree in BlocProvider so descendants can access the bloc.
BlocProvider(
create: (_) => CounterBloc(),
child: const CounterPage(),
);Reacting with BlocBuilder
BlocBuilder rebuilds widgets whenever a new state is emitted.
BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) => Text('Count: ' + state.count.toString()),
);Dispatching Events
Send events to the bloc with context.read<CounterBloc>().add(...).
FloatingActionButton(
onPressed: () => context.read<CounterBloc>().add(Increment()),
child: const Icon(Icons.add),
);BlocListener for Side Effects
Use BlocListener for one-time side effects like showing a SnackBar or navigating, where you do not want to rebuild UI.
BlocListener<CounterBloc, CounterState>(
listener: (context, state) {
if (state.count == 10) ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Reached 10!')),
);
},
child: child,
);Cubit: A Lighter BLoC
A Cubit drops events and exposes methods directly that call emit. Use it when full event classes feel like overkill.
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}Quick Check
Which widget should you use to trigger a one-time SnackBar without rebuilding UI on every state?
Recap
You learned the BLoC pattern:
- Events in, states out, via streams
- Bloc with on<Event> handlers, or a lighter Cubit
- BlocProvider, BlocBuilder and BlocListener
BLoC gives you clean, testable separation of logic and UI for complex apps.
Ucz się Dart dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 22
- Lekcje
- 88
Często zadawane pytania
Czy lekcja „Wzorzec BLoC ze Streams” jest bezpłatna?
Tak — pełny tekst „Wzorzec BLoC ze Streams” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Flutter Mobile Development, przejdź na CoddyKit PRO. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.
Co nauczysz się w „Wzorzec BLoC ze Streams”?
Poznaj wzorzec BLoC (Business Logic Component) we Flutterze, aby oddzielić logikę biznesową od interfejsu za pomocą zdarzeń, stanów i strumieni. Ćwiczysz Flutter Mobile Development z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Flutter Mobile Development?
Nie wymagamy żadnego doświadczenia. Flutter Mobile Development w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Wzorzec BLoC ze Streams”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Flutter Mobile Development?
Tak. Każda lekcja Flutter Mobile Development zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- setState i InheritedWidget
- Podstawy pakietu Provider
- Riverpod do zarządzania stanem
- Wzorzec BLoC ze Streams