FutureBuilder, StreamBuilder and the Repository Pattern
FutureBuilder
FutureBuilder listens to a Future and rebuilds when it completes. The snapshot tells you the current situation.
dart
FutureBuilder<List<Todo>>(
future: _future, // created once in initState
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return ErrorView(message: '${snapshot.error}', onRetry: _reload);
}
final items = snapshot.data ?? [];
if (items.isEmpty) {
return const Center(child: Text('Nothing here yet'));
}
return ListView(children: items.map((t) => Text(t.title)).toList());
},
)
| Snapshot property | Meaning |
|---|---|
connectionState | none, waiting, active or done |
hasData / data | The result |
hasError / error | The failure |
Always Handle Four States
- Loading: spinner or skeleton
- Error: message and a retry button
- Empty: friendly text
- Data: the real UI
Retry and Refresh
dart
void _reload() {
setState(() {
_future = repository.getTodos(); // assign a NEW future
});
}
Common bug: Writing
future: repository.getTodos() directly inside build creates a new request on every rebuild, which can cause an endless loading loop. Keep the future in a variable.
StreamBuilder
dart
StreamBuilder<int>(
stream: Stream.periodic(const Duration(seconds: 1), (i) => i),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Waiting...');
return Text('Seconds: ${snapshot.data}', style: const TextStyle(fontSize: 32));
},
)
Use StreamBuilder for live data, such as Firebase Firestore, sensors or WebSockets.
The Repository Pattern
A repository is a class that hides where the data comes from (network, database or cache). The rest of the app only asks the repository.
dart
abstract class TodoRepository {
Future<List<Todo>> getTodos();
Future<Todo> addTodo(String title);
}
class ApiTodoRepository implements TodoRepository {
final Dio _dio;
ApiTodoRepository(this._dio);
@override
Future<List<Todo>> getTodos() async {
final r = await _dio.get('/todos', queryParameters: {'_limit': 20});
return (r.data as List).map((e) => Todo.fromJson(e as Map<String, dynamic>)).toList();
}
@override
Future<Todo> addTodo(String title) async {
final r = await _dio.post('/todos', data: {'title': title, 'completed': false});
return Todo.fromJson(r.data as Map<String, dynamic>);
}
}
// For tests or offline demos
class FakeTodoRepository implements TodoRepository {
@override
Future<List<Todo>> getTodos() async =>
[const Todo(id: 1, title: 'Test', completed: false)];
@override
Future<Todo> addTodo(String title) async =>
Todo(id: 2, title: title, completed: false);
}
| Benefit | Why |
|---|---|
| Clean widgets | No HTTP code inside the UI |
| Easy tests | Swap in a fake repository |
| Easy changes | Switch from REST to Firebase in one place |
Conclusion
Use FutureBuilder and StreamBuilder for async UI, create futures once and handle all four states. Put API code in repositories.
Quick Summary: FutureBuilder shows async results, keep the Future in a variable, handle loading, error, empty and data, and use repositories for data access.

