Flutter
loading and error
Handle states with ConnectionState.waiting and hasError.
loading and error
Two cases are common in FutureBuilder: while ConnectionState.waiting show a loading indicator, and when snapshot.hasError show an error message.
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
These two checks improve the user experience.
Error handling with hasError
snapshot.hasError becomes true when the Future throws an error. In this case, you show the error with snapshot.error.
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
If the error is not caught, the app may crash.
Exercise Handle loading, error and data states
The veriGetir async method should wait 100 ms and return 'Hazır'. In FutureBuilder<String>: while waiting show CircularProgressIndicator, if hasError show Text('hata'), otherwise show Text(snapshot.data!). In main, call print('başladı').
Show example solution
import 'package:flutter/material.dart';
Future<String> veriGetir() async {
await Future.delayed(Duration(milliseconds: 100));
return 'Hazır';
}
void main() {
print('başladı');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<String>(
future: veriGetir(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('hata');
}
return Text(snapshot.data!);
},
),
),
);
}
}
Test yourself
-
Which indicator is used for loading state in FutureBuilder?
- Scaffold
- Text
- CircularProgressIndicator
- AppBar
Show answer
CircularProgressIndicator — In ConnectionState.waiting, a loading indicator such as CircularProgressIndicator is shown.
-
Add the loading indicator
if (snapshot.connectionState == ConnectionState.waiting) {
return ____();
}
Show answer
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
-
loading and error parts
- ConnectionState.waiting
- Loading phase
- hasError
- True when Future throws
- CircularProgressIndicator
- Loading indicator
- snapshot.error
- Thrown error
Next lesson: Future re-run