Skip to content

Instantly share code, notes, and snippets.

@nicol-ograve
Created March 2, 2025 11:10
Show Gist options
  • Save nicol-ograve/6cf94c6accda12164b6a29579deb683e to your computer and use it in GitHub Desktop.
Save nicol-ograve/6cf94c6accda12164b6a29579deb683e to your computer and use it in GitHub Desktop.
import 'dart:async';
// Funzione che simula il recupero di dati da un database dopo 2 secondi
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // Simula ritardo
return "Dati ricevuti dal database!";
}
// Funzione che simula un errore
Future<String> fetchWithError() async {
await Future.delayed(Duration(seconds: 1));
throw Exception("Errore nel recupero dei dati!");
}
// Funzione principale che usa async-await e gestisce gli errori
Future<void> fetchDataAndHandle() async {
try {
print("Recupero dati in corso...");
String data = await fetchData(); // Attende il Future
print("Successo: $data");
} catch (e) {
print("Errore: $e");
}
}
// Funzione che gestisce un errore in modo asincrono
Future<void> fetchDataWithErrorHandling() async {
try {
print("Tentativo di recupero con errore...");
String data = await fetchWithError();
print("Successo: $data");
} catch (e) {
print("Errore gestito correttamente: $e");
} finally {
print("Operazione completata (con o senza successo).");
}
}
void main() async {
await fetchDataAndHandle();
print("\n-----------------\n");
await fetchDataWithErrorHandling();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment