FutureBuilder in Flutter: solved exercise for loading states

FutureBuilder in Flutter: solved exercise

If you are looking for FutureBuilder in Flutter, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Problem statement

Build a screen with:

  • show loading spinner
  • show error message on failure
  • render list when data is ready

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: FutureBuilderPage()));

class FutureBuilderPage extends StatelessWidget {
  const FutureBuilderPage({super.key});

  Future<List<String>> loadItems() async {
    await Future.delayed(const Duration(seconds: 2));
    return ['Flutter', 'Dart', 'Widgets', 'State'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('FutureBuilder')),
      body: FutureBuilder<List<String>>(
        future: loadItems(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return const Center(child: Text('Error cargando datos'));
          }
          final items = snapshot.data ?? [];
          return ListView.builder(
            itemCount: items.length,
            itemBuilder: (_, i) => ListTile(title: Text(items[i])),
          );
        },
      ),
    );
  }
}

Expected result

The UI transitions correctly between waiting, error, and success states.

Common mistakes

  • Creating a new Future on every build.
  • Skipping hasError handling.
  • Not handling empty data states.

Practical use

Great for initial data fetches in profile, dashboard, and setup screens.

Guided practice and next step

FAQ

Does FutureBuilder replace Provider or Bloc?

No. It solves one async rendering case, not full app state management.

Can I refresh data manually?

Yes, trigger a new Future and rebuild the widget.

When should I avoid FutureBuilder?

When data is continuous or state is shared across many screens.