Learn/Async UI & APIs/Error Handling & Loading States

Error Handling & Loading States

Handle errors, show loading indicators, and build retry logic

6 min~7 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. try-catch-finally in Async Code
  2. 2. Pull to Refresh
  3. 3. Adding a Timeout
  4. 4. Error UX Principles
  5. 5. This Lesson In Simple Words
  6. 6. Your level focus
  7. 7. One practical habit
  8. 8. Deep Understanding Guide
  9. 9. Why this lesson matters
  10. 10. Study flow for better retention
  11. 11. Quick Glossary

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

Error Handling & Loading States

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.

dart
1// The three states every async screen needs
2class _UserScreenState extends State<UserScreen> {
3 bool _isLoading = true;
4 String? _errorMessage;
5 User? _user;
6
7 @override
8 void initState() {
9 super.initState();
10 _loadUser();
11 }
12
13 Future<void> _loadUser() async {
14 // Reset to loading state
15 setState(() {
16 _isLoading = true;
17 _errorMessage = null;
18 });
19
20 try {
21 final user = await fetchUser(widget.userId);
22 if (mounted) {
23 setState(() {
24 _user = user;
25 _isLoading = false;
26 });
27 }
28 } catch (e) {
29 if (mounted) {
30 setState(() {
31 _errorMessage = 'Could not load profile. Please try again.';
32 _isLoading = false;
33 });
34 }
35 }
36 }
37
38 @override
39 Widget build(BuildContext context) {
40 if (_isLoading) {
41 return const Center(child: CircularProgressIndicator());
42 }
43
44 if (_errorMessage != null) {
45 return Center(
46 child: Column(
47 mainAxisSize: MainAxisSize.min,
48 children: [
49 const Icon(Icons.error_outline, size: 48, color: Colors.red),
50 const SizedBox(height: 16),
51 Text(_errorMessage!, textAlign: TextAlign.center),
52 const SizedBox(height: 16),
53 ElevatedButton(
54 onPressed: _loadUser, // retry button
55 child: const Text('Retry'),
56 ),
57 ],
58 ),
59 );
60 }
61
62 return UserCard(user: _user!);
63 }
64}

try-catch-finally in Async Code

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.

dart
1Future<void> submitForm() async {
2 setState(() => _isSubmitting = true);
3
4 try {
5 // Attempt the network call
6 await api.createPost(title: _title, body: _body);
7
8 if (mounted) {
9 // Show success feedback
10 ScaffoldMessenger.of(context).showSnackBar(
11 const SnackBar(content: Text('Post created successfully')),
12 );
13 Navigator.pop(context); // go back on success
14 }
15 } on SocketException {
16 // No internet connection
17 _showError('No internet connection. Check your network.');
18 } on TimeoutException {
19 // Server took too long
20 _showError('Request timed out. Try again later.');
21 } on FormatException {
22 // Bad response format
23 _showError('Unexpected server response.');
24 } catch (e) {
25 // Any other error
26 _showError('Something went wrong. Please try again.');
27 } finally {
28 // Always stop loading indicator
29 if (mounted) {
30 setState(() => _isSubmitting = false);
31 }
32 }
33}
34
35void _showError(String message) {
36 if (mounted) {
37 setState(() => _errorMessage = message);
38 }
39}

Pull to Refresh

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.

dart
1// Pull to refresh wrapper
2RefreshIndicator(
3 onRefresh: _loadUsers, // must return Future<void>
4 child: ListView.builder(
5 itemCount: _users.length,
6 itemBuilder: (context, index) {
7 return ListTile(
8 title: Text(_users[index].name),
9 subtitle: Text(_users[index].email),
10 );
11 },
12 ),
13)
14
15// The refresh function
16Future<void> _loadUsers() async {
17 try {
18 final users = await api.getUsers();
19 if (mounted) {
20 setState(() => _users = users);
21 }
22 } catch (e) {
23 if (mounted) {
24 ScaffoldMessenger.of(context).showSnackBar(
25 const SnackBar(content: Text('Failed to refresh')),
26 );
27 }
28 }
29}

Adding a Timeout

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.

dart
1import 'dart:async';
2
3Future<User> fetchUserWithTimeout(int id) async {
4 final response = await http
5 .get(Uri.parse('https://api.example.com/users/$id'))
6 .timeout(
7 const Duration(seconds: 10),
8 onTimeout: () => throw TimeoutException('Server not responding'),
9 );
10
11 if (response.statusCode == 200) {
12 return User.fromJson(jsonDecode(response.body));
13 }
14 throw Exception('Server error: ${response.statusCode}');
15}

User-Friendly Error Messages

💡 User-Friendly Error Messages

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.

Always Check mounted

⚠️ Always Check mounted

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.

Error UX Principles

A good error flow is transparent and recoverable:

  • explain what failed in user language
  • preserve user context when possible
  • offer retry for transient failures

Users accept occasional failures when recovery is clear and quick.

Async Screen Resilience Checklist

  • Loading, success, empty, and error states all exist.
  • Retry actions are visible and functional.
  • Timeouts and offline behavior are handled explicitly.
  • Technical errors are logged while user messages stay simple.

This Lesson In Simple Words

Handle errors, show loading indicators, and build retry logic. State is data that changes over time and controls what users see on the screen.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Keep state as close as possible to where it is used, then lift it only when sharing is required.

Deep Understanding Guide

Why this lesson matters

State management is the difference between predictable apps and hard-to-debug UI behavior.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Trace one user action from button tap to state update to rebuilt UI.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Calling setState high in the tree when only a small part needs refresh.
  • Keeping duplicated state in multiple widgets without a single source of truth.
  • Mutating collections directly and expecting UI updates automatically.
  • Choosing a heavy state library before understanding simple local state.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one feature with local setState, then refactor it to Provider or Riverpod.
  • Create loading, success, and error states for one async user flow.
  • Write a small state diagram for a login form and implement it.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What are the three states an async screen typically needs to handle?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • context: A handle to widget location and inherited data in the tree.
  • build: The method that describes UI for the current state.
  • bloc: An event-to-state pattern that separates logic from UI.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Error Handling & Loading States" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Calling setState high in the tree when only a small part needs refresh.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

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.

What does the finally block do in a try-catch-finally?

Finally always executes after try and catch complete, making it the right place for cleanup like hiding a loading indicator.

Which widget provides pull-to-refresh in Flutter?

RefreshIndicator wraps a scrollable widget and provides the standard pull-to-refresh gesture with a circular loading indicator.

How do you add a timeout to an HTTP request in Dart?

The .timeout() method on any Future throws a TimeoutException if the operation does not complete within the given Duration.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

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