AsyncSnapshot
- Flutter course
- Intermediate
- Lesson 22/99
- 4 min
Learn AsyncSnapshot connection states.
AsyncSnapshot
AsyncSnapshot carries the current state of the Future. ConnectionState gives the connection phase, data gives the result, and error gives the error.
snapshot.connectionState
snapshot.data
snapshot.errorInside builder, different widgets are shown based on these.
ConnectionState values
ConnectionState takes four values: none (not started), waiting (waiting), active (stream active), done (completed). For FutureBuilder, the most common are waiting and done.
if (snapshot.connectionState == ConnectionState.done) {
return Text(snapshot.data!);
}done indicates that the result is ready.
Practice Show result with ConnectionState.done
The veriGetir async method should wait 100 ms and return 'Tamamlandı'. In FutureBuilder<String>, if snapshot.connectionState == ConnectionState.done show the result, otherwise show 'bekle'. In main, call print('başladı').
Starter code
import 'package:flutter/material.dart';
Future<String> veriGetir() async {
await Future.delayed(Duration(milliseconds: 100));
return 'Tamamlandı';
}
void main() {
print('başladı');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
// FutureBuilder ile durum kontrolü yap
child: Text('bekle'),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
Future<String> veriGetir() async {
await Future.delayed(Duration(milliseconds: 100));
return 'Tamamlandı';
}
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.done) {
return Text(snapshot.data!);
}
return Text('bekle');
},
),
),
);
}
}Expected output
başladı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which property gives the connection state of AsyncSnapshot?
- snapshot.error
- snapshot.builder
- snapshot.data
- snapshot.connectionState Correct answer
Explanation: AsyncSnapshot's connectionState property gives the connection phase (none, waiting, active, done).
2 Add ConnectionState check
if (snapshot.connectionState == ConnectionState.____) {
return Text(snapshot.data!);
}
if (snapshot.connectionState == ConnectionState.done) {
return Text(snapshot.data!);
}
Explanation: ConnectionState.done occurs when the Future completes; at this stage snapshot.data carries the result.
3 AsyncSnapshot parts
| Term | Meaning |
|---|---|
AsyncSnapshot |
Carries Future's current state |
ConnectionState |
Gives connection phase |
data |
Future's result |
error |
Error if Future throws |