What are the three states an async screen typically needs to handle?
Every screen that loads data should show a loading indicator while fetching, display the data on success, and show an error message with a retry option on failure.
Handle errors, show loading indicators, and build retry logic
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
Every app that fetches data from the internet needs to deal with three realities: the data is still loading, the request succeeded, or something went wrong. A well-built app handles all three states gracefully so the user always knows what is happening. This lesson covers try-catch patterns for async code, how to show proper loading indicators, how to display user-friendly error messages, and how to let the user retry a failed request.
1// The three states every async screen needs2class _UserScreenState extends State<UserScreen> {3bool _isLoading = true;4String? _errorMessage;5User? _user;67@override8void initState() {9super.initState();10_loadUser();11}1213Future<void> _loadUser() async {14// Reset to loading state15setState(() {16_isLoading = true;17_errorMessage = null;18});1920try {21final user = await fetchUser(widget.userId);22if (mounted) {23setState(() {24_user = user;25_isLoading = false;26});27}28} catch (e) {29if (mounted) {30setState(() {31_errorMessage = 'Could not load profile. Please try again.';32_isLoading = false;33});34}35}36}3738@override39Widget build(BuildContext context) {40if (_isLoading) {41return const Center(child: CircularProgressIndicator());42}4344if (_errorMessage != null) {45return Center(46child: Column(47mainAxisSize: MainAxisSize.min,48children: [49const Icon(Icons.error_outline, size: 48, color: Colors.red),50const SizedBox(height: 16),51Text(_errorMessage!, textAlign: TextAlign.center),52const SizedBox(height: 16),53ElevatedButton(54onPressed: _loadUser, // retry button55child: const Text('Retry'),56),57],58),59);60}6162return UserCard(user: _user!);63}64}
When you call an API, many things can go wrong: the device has no internet, the server is down, the response format changed, or the request timed out. Wrapping your async calls in try-catch lets you handle these failures without crashing the app. The finally block is useful for cleanup that should happen regardless of success or failure, like hiding a loading spinner.
1Future<void> submitForm() async {2setState(() => _isSubmitting = true);34try {5// Attempt the network call6await api.createPost(title: _title, body: _body);78if (mounted) {9// Show success feedback10ScaffoldMessenger.of(context).showSnackBar(11const SnackBar(content: Text('Post created successfully')),12);13Navigator.pop(context); // go back on success14}15} on SocketException {16// No internet connection17_showError('No internet connection. Check your network.');18} on TimeoutException {19// Server took too long20_showError('Request timed out. Try again later.');21} on FormatException {22// Bad response format23_showError('Unexpected server response.');24} catch (e) {25// Any other error26_showError('Something went wrong. Please try again.');27} finally {28// Always stop loading indicator29if (mounted) {30setState(() => _isSubmitting = false);31}32}33}3435void _showError(String message) {36if (mounted) {37setState(() => _errorMessage = message);38}39}
Pull-to-refresh is a standard mobile pattern that lets users swipe down to reload data. Flutter provides the RefreshIndicator widget that wraps a scrollable widget and handles the pull-down gesture automatically. You just give it an onRefresh callback that returns a Future.
1// Pull to refresh wrapper2RefreshIndicator(3onRefresh: _loadUsers, // must return Future<void>4child: ListView.builder(5itemCount: _users.length,6itemBuilder: (context, index) {7return ListTile(8title: Text(_users[index].name),9subtitle: Text(_users[index].email),10);11},12),13)1415// The refresh function16Future<void> _loadUsers() async {17try {18final users = await api.getUsers();19if (mounted) {20setState(() => _users = users);21}22} catch (e) {23if (mounted) {24ScaffoldMessenger.of(context).showSnackBar(25const SnackBar(content: Text('Failed to refresh')),26);27}28}29}
If the server is slow, you do not want the user waiting forever. You can add a timeout to any Future using the .timeout() method. If the operation does not complete within the given duration, it throws a TimeoutException that you can catch and handle.
1import 'dart:async';23Future<User> fetchUserWithTimeout(int id) async {4final response = await http5.get(Uri.parse('https://api.example.com/users/$id'))6.timeout(7const Duration(seconds: 10),8onTimeout: () => throw TimeoutException('Server not responding'),9);1011if (response.statusCode == 200) {12return User.fromJson(jsonDecode(response.body));13}14throw Exception('Server error: ${response.statusCode}');15}
Never show raw error messages or stack traces to users. Instead, translate technical errors into helpful messages like "No internet connection" or "Could not load data. Please try again." and always provide a way to retry.
After every await call, the widget may have been removed from the screen. Always check if (mounted) before calling setState in async methods to avoid the "setState called after dispose" error.
A good error flow is transparent and recoverable:
Users accept occasional failures when recovery is clear and quick.
Handle errors, show loading indicators, and build retry logic. State is data that changes over time and controls what users see on the screen.
Connect each concept to real app features you can build.
Keep state as close as possible to where it is used, then lift it only when sharing is required.
State management is the difference between predictable apps and hard-to-debug UI behavior.
Every screen that loads data should show a loading indicator while fetching, display the data on success, and show an error message with a retry option on failure.
Finally always executes after try and catch complete, making it the right place for cleanup like hiding a loading indicator.
RefreshIndicator wraps a scrollable widget and provides the standard pull-to-refresh gesture with a circular loading indicator.
The .timeout() method on any Future throws a TimeoutException if the operation does not complete within the given Duration.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue