0Pricing
Flutter Mobile Development · Lezione

Pattern BLoC con Streams

Impari il pattern BLoC (Business Logic Component) in Flutter per separare la logica di business dall’interfaccia utente usando eventi, stati e stream.

Pattern BLoC con Streams è una lezione Flutter Mobile Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flutter Mobile Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flutter Mobile Development include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Pattern BLoC con Streams» è gratuita?

Sì — il testo completo di «Pattern BLoC con Streams» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flutter Mobile Development, passa a CoddyKit PRO. Il corso Flutter Mobile Development include 4 lezioni in totale.

Cosa imparerò in «Pattern BLoC con Streams»?

Impari il pattern BLoC (Business Logic Component) in Flutter per separare la logica di business dall’interfaccia utente usando eventi, stati e stream. Eserciti Flutter Mobile Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flutter Mobile Development?

Non è richiesta alcuna esperienza precedente. Flutter Mobile Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Pattern BLoC con Streams»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flutter Mobile Development?

Sì. Ogni lezione Flutter Mobile Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. setState e InheritedWidget
  2. Nozioni di base sul package Provider
  3. Riverpod per la gestione dello stato
  4. Pattern BLoC con Streams
← Torna a Flutter Mobile Development