Learn/Async UI & APIs/FutureBuilder

FutureBuilder

Build UI based on async operations

5 min~5 min read+30 FX

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

Table of Contents

  1. 1. Complete Example
  2. 2. FutureBuilder Design Pattern
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. 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

FutureBuilder Widget

FutureBuilder is a widget that listens to a Future and automatically rebuilds the UI whenever the state of that Future changes. It tracks three main phases: loading (the Future is still running), success (the Future completed with data), and error (the Future threw an exception). This means you do not need to manually call setState or track loading flags yourself - FutureBuilder handles all of that for you.

dart
1FutureBuilder<User>(
2 future: fetchUser(), // The async operation
3 builder: (context, snapshot) {
4 // Loading state
5 if (snapshot.connectionState == ConnectionState.waiting) {
6 return CircularProgressIndicator();
7 }
8
9 // Error state
10 if (snapshot.hasError) {
11 return Text('Error: ${snapshot.error}');
12 }
13
14 // Success state
15 if (snapshot.hasData) {
16 final user = snapshot.data!;
17 return Text('Hello, ${user.name}');
18 }
19
20 // No data yet
21 return Text('No data');
22 },
23)

Complete Example

Here is a full example that fetches a user from an API and displays it. Notice how the Future is stored in initState so it only runs once, not on every rebuild. The builder uses a switch statement to handle every possible connection state.

dart
1class UserProfile extends StatefulWidget {
2 @override
3 _UserProfileState createState() => _UserProfileState();
4}
5
6class _UserProfileState extends State<UserProfile> {
7 late Future<User> _userFuture;
8
9 @override
10 void initState() {
11 super.initState();
12 _userFuture = fetchUser(); // Call once in initState
13 }
14
15 @override
16 Widget build(BuildContext context) {
17 return Scaffold(
18 appBar: AppBar(title: Text('Profile')),
19 body: FutureBuilder<User>(
20 future: _userFuture, // Use stored future
21 builder: (context, snapshot) {
22 switch (snapshot.connectionState) {
23 case ConnectionState.none:
24 return SizedBox.shrink();
25 case ConnectionState.active:
26 case ConnectionState.waiting:
27 return Center(child: CircularProgressIndicator());
28 case ConnectionState.done:
29 if (snapshot.hasError) {
30 return Center(child: Text('Something went wrong'));
31 }
32 return UserCard(user: snapshot.data!);
33 }
34 },
35 ),
36 );
37 }
38}

Important

⚠️ Important

Never call the async function directly in the future parameter. If you write future: fetchUser(), a brand new Future is created on every rebuild, causing infinite API calls. Always store the Future in a variable inside initState and pass that variable to the future parameter instead.

FutureBuilder Design Pattern

Treat FutureBuilder screens as state machines:

  • loading UI for waiting phase
  • success UI for data phase
  • error UI with retry capability

This keeps async UX predictable and easy to test.

FutureBuilder Checklist

  • Future is created once in initState or memoized source.
  • All connection states are handled intentionally.
  • Error state provides clear retry path.
  • No expensive logic is repeated inside builder unnecessarily.

This Lesson In Simple Words

Build UI based on async operations. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "When is ConnectionState.waiting true?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • async: Code that runs over time without blocking the UI thread.
  • future: A single asynchronous result delivered later.

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 "FutureBuilder" 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: Ignoring null safety and forcing values with ! without checking data flow.
  • 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

When is ConnectionState.waiting true?

ConnectionState.waiting means the Future has not completed yet.

Where should you call the async function for FutureBuilder?

Store the Future in initState to prevent multiple calls on rebuild.

What does snapshot.hasData check?

hasData returns true when the Future has completed successfully with a non-null result.

What type does FutureBuilder<User> expect as its future?

FutureBuilder<T> expects a Future<T> parameter matching its type parameter.

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