Flutter
AsyncSnapshot
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.error
Inside 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.
Exercise 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ı').
Show example 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');
},
),
),
);
}
}
Test yourself
-
Which property gives the connection state of AsyncSnapshot?
- snapshot.error
- snapshot.builder
- snapshot.data
- snapshot.connectionState
Show answer
snapshot.connectionState — AsyncSnapshot's connectionState property gives the connection phase (none, waiting, active, done).
-
Add ConnectionState check
if (snapshot.connectionState == ConnectionState.____) {
return Text(snapshot.data!);
}
Show answer
if (snapshot.connectionState == ConnectionState.done) {
return Text(snapshot.data!);
}
-
AsyncSnapshot parts
- AsyncSnapshot
- Carries Future's current state
- ConnectionState
- Gives connection phase
- data
- Future's result
- error
- Error if Future throws
Next lesson: loading and error