Flutter Mobile Development · Lezione

Programmazione asincrona con Futures e async/await

Gestisca le operazioni differite in Dart e Flutter usando Futures, async, await e la gestione degli errori.

Lezione 4 di 413 passaggi

Programmazione asincrona con Futures e async/await è 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.

Why Async?

Apps fetch data, read files, and wait on timers. Blocking would freeze the UI, so Dart uses asynchronous programming to stay responsive.

The Future Type

A Future is a value that’ll arrive later. It’s either uncompleted, completed with a value, or completed with an error.

Future<String> fetchName() {
  return Future.delayed(
    Duration(seconds: 1),
    () => "Ada",
  );
}

async and await

Mark a function async and use await to pause until a Future completes — async code that reads top-to-bottom like normal.

Future<void> main() async {
  print("start");
  String name = await fetchName();
  print("Hello, " + name);
}

await Suspends, Not Blocks

Key point: await suspends, it doesn’t block. The event loop keeps handling other work, so the UI stays responsive.

Returning Values

An async function always returns a Future. A plain return inside it just completes that Future with the value.

Future<int> doubleIt(int x) async {
  return x * 2;  // becomes Future<int>
}

Error Handling

Wrap awaited calls in try/catch to handle failures — exactly like catching synchronous exceptions.

try {
  var data = await fetchData();
} catch (e) {
  print("Failed: " + e.toString());
}

Chaining with then

Without async/await, you attach callbacks with then and catchError. Async/await is clearer but compiles to the same idea.

fetchName()
    .then((n) => print(n))
    .catchError((e) => print("error"));

Running in Parallel

Use Future.wait to launch several Futures at once and await them together — faster than awaiting one after another.

var results = await Future.wait([
  fetchA(),
  fetchB(),
]);

FutureBuilder in Flutter

The FutureBuilder widget rebuilds your UI as a Future goes from loading to done — so you show spinners and results declaratively.

FutureBuilder<String>(
  future: fetchName(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return CircularProgressIndicator();
    return Text(snapshot.data!);
  },
)

Streams: Many Values

A Future yields one value; a Stream yields many over time. Listen with await for or a StreamBuilder.

Stream<int> counter() async* {
  for (var i = 0; i < 3; i++) {
    yield i;
  }
}

Putting It Together

Putting it together: Futures for one-off results, async/await for clean code, try/catch for errors, and FutureBuilder to bind async data to widgets.

Quick Check

One quick check on Dart’s Future and async/await before you move on.

Recap

You’ve got Dart async: Future for later values, async/await for readable code, try/catch for errors, and Future.wait plus FutureBuilder.

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 «Programmazione asincrona con Futures e async/await» è gratuita?

Sì — il testo completo di «Programmazione asincrona con Futures e async/await» è 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 «Programmazione asincrona con Futures e async/await»?

Gestisca le operazioni differite in Dart e Flutter usando Futures, async, await e la gestione degli errori. 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 «Programmazione asincrona con Futures e async/await»?

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. Ecosistema e configurazione di Flutter
  2. Fondamenti di Dart per Flutter
  3. Creazione della prima app Flutter
  4. Programmazione asincrona con Futures e async/await
← Torna a Flutter Mobile Development