Flutter Mobile Development · Lezione

Stream e dati reattivi

Impari a lavorare con gli Stream di Dart in Flutter per gestire dati asincroni continui, come aggiornamenti in tempo reale, socket e interfacce reattive.

Lezione 4 di 413 passaggi

Stream e dati reattivi è 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.

Beyond a Single Future

A Future gives you one value later. A Stream gives you many values over time.

  • WebSocket messages
  • Sensor readings
  • Live database updates

Streams are the reactive backbone of async Dart.

Listening to a Stream

Subscribe to a stream with listen, supplying callbacks for data, errors and completion.

stream.listen(
  (data) => print('Got: ' + data.toString()),
  onError: (e) => print('Error: ' + e.toString()),
  onDone: () => print('Done'),
);

Creating Streams with async*

An async generator uses async* and yield to emit values.

Stream<int> countTo(int n) async* {
  for (var i = 1; i <= n; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
  }
}

await for

Inside an async function you can iterate a stream with await for, processing each value as it arrives.

Future<void> run() async {
  await for (final value in countTo(3)) {
    print(value);
  }
}

Single vs Broadcast

A single-subscription stream allows one listener. A broadcast stream allows many. Convert with asBroadcastStream().

final broadcast = controller.stream.asBroadcastStream();
broadcast.listen((v) => print('A: ' + v.toString()));
broadcast.listen((v) => print('B: ' + v.toString()));

StreamController

A StreamController lets you push values into a stream from your own code.

final controller = StreamController<String>();
controller.add('hello');
controller.add('world');
controller.close();

Transforming Streams

Streams have functional operators like map, where and take.

stream
  .where((n) => n.isEven)
  .map((n) => n * 10)
  .take(5)
  .listen(print);

StreamBuilder Widget

In the UI, StreamBuilder rebuilds whenever the stream emits a new value.

StreamBuilder<int>(
  stream: countTo(5),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return const CircularProgressIndicator();
    return Text('Value: ' + snapshot.data.toString());
  },
);

Reading the Snapshot

The AsyncSnapshot tells you the connection state and whether data or an error is present.

  • snapshot.connectionState
  • snapshot.hasData / snapshot.data
  • snapshot.hasError / snapshot.error
if (snapshot.hasError) return Text('Error: ' + snapshot.error.toString());

Cancelling Subscriptions

Always cancel subscriptions in dispose to avoid memory leaks.

late StreamSubscription sub;

@override
void dispose() {
  sub.cancel();
  super.dispose();
}

Backpressure & Errors

Streams can emit errors mid-flow. Handle them with handleError so one bad event does not kill the whole pipeline.

stream
  .handleError((e) => print('Skipped: ' + e.toString()))
  .listen(print);

Quick Check

Which widget rebuilds your UI automatically as a stream emits new values?

Recap

You learned to work with Streams:

  • async* / yield and StreamController to create them
  • map / where / take to transform
  • StreamBuilder to drive reactive UI
  • Cancelling subscriptions and handling errors

Streams let your app react to continuous async data in real time.

Gratis per iniziare

Impara Dart con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
22
Lezioni
88

Domande Frequenti

La lezione «Stream e dati reattivi» è gratuita?

Sì — il testo completo di «Stream e dati reattivi» è 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 «Stream e dati reattivi»?

Impari a lavorare con gli Stream di Dart in Flutter per gestire dati asincroni continui, come aggiornamenti in tempo reale, socket e interfacce reattive. 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 «Stream e dati reattivi»?

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. Future e async/await
  2. Richieste HTTP e JSON
  3. Gestione degli errori nelle operazioni asincrone
  4. Stream e dati reattivi
← Torna a Flutter Mobile Development