Flutter
What is FutureBuilder?
Bind async results to UI with FutureBuilder.
What is FutureBuilder?
FutureBuilder is a widget that binds a Future's result to the UI. The future parameter takes the Future to watch, and builder takes the function that converts the result to a widget.
FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'empty');
},
)
When the Future completes, the builder is called again.
Accessing data with snapshot
The builder function receives an AsyncSnapshot. snapshot.data gives the Future's result. If there is no result yet, it returns null; so a default value is usually provided with ??.
builder: (context, snapshot) {
return Text(snapshot.data ?? 'loading');
}
The snapshot carries the Future's current state.
Exercise Display data with FutureBuilder
The veriGetir async method should wait 100 ms and return 'Merhaba FutureBuilder'. In Ekrani stateful widget, hold a _future field and in initState call print('ekran açıldı'). In build, display snapshot.data ?? 'bekle' with FutureBuilder<String>.
Show example solution
import 'package:flutter/material.dart';
Future<String> veriGetir() async {
await Future.delayed(Duration(milliseconds: 100));
return 'Merhaba FutureBuilder';
}
class Ekrani extends StatefulWidget {
@override
_EkraniState createState() => _EkraniState();
}
class _EkraniState extends State<Ekrani> {
late Future<String> _future;
@override
void initState() {
super.initState();
print('ekran açıldı');
_future = veriGetir();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<String>(
future: _future,
builder: (context, snapshot) {
return Text(snapshot.data ?? 'bekle');
},
),
),
);
}
}
void main() => runApp(MaterialApp(home: Ekrani()));
Test yourself
-
Which parameter takes the Future to watch in FutureBuilder?
Show answer
future — FutureBuilder's future parameter takes the Future to watch; builder converts the result to a widget.
-
Bind FutureBuilder's future
FutureBuilder<String>(
____: veriGetir(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'boş');
},
)
Show answer
FutureBuilder<String>(
future: veriGetir(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'boş');
},
)
-
FutureBuilder parts
- FutureBuilder
- Widget binding Future to UI
- future
- Parameter taking the Future
- builder
- Function converting result to widget
- snapshot
- Object carrying Future's current state
Next lesson: AsyncSnapshot