Error Handling in Asynchronous Dart
When working with asynchronous Dart code in Flutter, you need to handle errors gracefully to avoid app crashes and keep the user experience smooth. Dart provides familiar try and catch blocks for catching exceptions, even when using async and await. By wrapping your asynchronous calls in a try/catch, you can respond to errors in a controlled way, such as by showing a message or updating the UI, instead of letting the app fail unexpectedly.
main.dart
123456789101112131415161718192021222324252627282930313233343536373839404142// main.dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); Future<String> fetchData() async { await Future.delayed(const Duration(seconds: 1)); throw Exception('Failed to load data'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Async Error Handling')), body: Center( child: FutureBuilder<String>( future: (() async { try { return await fetchData(); } catch (e) { return 'Error: ${e.toString()}'; } })(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasData) { return Text(snapshot.data!); } else { return const Text('No data'); } }, ), ), ), ); } }
When dealing with asynchronous operations in Flutter, errors can occur in both Futures and Streams. For Futures, you can use try/catch with async/await, or handle errors with the catchError method. For Streams, you can provide an onError handler when listening to the stream. In Flutter widgets, such as FutureBuilder and StreamBuilder, you can display error messages by checking the error property in the snapshot, allowing you to show feedback to users if something goes wrong.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738// main.dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); Future<String> loadData() async { await Future.delayed(const Duration(seconds: 1)); throw Exception('Network error'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('FutureBuilder Error Example')), body: Center( child: FutureBuilder<String>( future: loadData(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else if (snapshot.hasData) { return Text('Result: ${snapshot.data}'); } else { return const Text('No result'); } }, ), ), ), ); } }
If you do not catch exceptions in your asynchronous code, your Flutter app may crash or display a blank screen. Always handle errors to keep your app stable and user friendly.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Mahtavaa!
Completion arvosana parantunut arvoon 7.14
Error Handling in Asynchronous Dart
Pyyhkäise näyttääksesi valikon
When working with asynchronous Dart code in Flutter, you need to handle errors gracefully to avoid app crashes and keep the user experience smooth. Dart provides familiar try and catch blocks for catching exceptions, even when using async and await. By wrapping your asynchronous calls in a try/catch, you can respond to errors in a controlled way, such as by showing a message or updating the UI, instead of letting the app fail unexpectedly.
main.dart
123456789101112131415161718192021222324252627282930313233343536373839404142// main.dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); Future<String> fetchData() async { await Future.delayed(const Duration(seconds: 1)); throw Exception('Failed to load data'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Async Error Handling')), body: Center( child: FutureBuilder<String>( future: (() async { try { return await fetchData(); } catch (e) { return 'Error: ${e.toString()}'; } })(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasData) { return Text(snapshot.data!); } else { return const Text('No data'); } }, ), ), ), ); } }
When dealing with asynchronous operations in Flutter, errors can occur in both Futures and Streams. For Futures, you can use try/catch with async/await, or handle errors with the catchError method. For Streams, you can provide an onError handler when listening to the stream. In Flutter widgets, such as FutureBuilder and StreamBuilder, you can display error messages by checking the error property in the snapshot, allowing you to show feedback to users if something goes wrong.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738// main.dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); Future<String> loadData() async { await Future.delayed(const Duration(seconds: 1)); throw Exception('Network error'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('FutureBuilder Error Example')), body: Center( child: FutureBuilder<String>( future: loadData(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else if (snapshot.hasData) { return Text('Result: ${snapshot.data}'); } else { return const Text('No result'); } }, ), ), ), ); } }
If you do not catch exceptions in your asynchronous code, your Flutter app may crash or display a blank screen. Always handle errors to keep your app stable and user friendly.
Kiitos palautteestasi!