What is a FutureBuilder?
In Flutter, FutureBuilder is a widget that responds to changes in state or dependencies by building itself based on the most recent snapshot of a Future. With FutureBuilder, we can run asynchronous functions and update our UI based on the function’s output.
Syntax
FutureBuilder({Key? key,Future<T>? future,T? initialData,required AsyncWidgetBuilder<T> builder,})
Note: The
buildermust not be null.
Parameters
key: This property controls how another replaces one widget.future: This property represents theFuturewhose snapshot can be accessed by the builder function.initialData: This property represents the data that will be utilized to build the snapshots until a non-null Future has been completed.builder: This property represents the current build strategy.
Future states
The following are the states used to determine the future’s current state when using a FutureBuilder widget:
-
ConnectionState.none: This indicates thatinitialDatais being utilized as thedefaultValueand that the future is null. -
ConnectionState.active: This indicates that although the future is not null, it has not yet been resolved. -
ConnectionState.waiting: This state indicates that the future is currently being resolved, and we’ll receive the outcome shortly. -
ConnectionState.done: This denotes the completion of the future.
Code
The following code shows how to use a FutureBuilder.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: HomePage()));
}
class HomePage extends StatelessWidget {
const HomePage({Key key}) : super(key: key);
Future<String> getWriterName() {
return Future.delayed(const Duration(seconds: 3), () => "Maria Elijah");
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.deepPurpleAccent,
title: const Text('Flutter FutureBuilder'),
),
body: SizedBox(
width: double.infinity,
child: Center(
child: FutureBuilder(
future: getWriterName(),
initialData: "Code sample",
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: Colors.deepPurpleAccent,
),
);
}
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text(
'An ${snapshot.error} occurred',
style: const TextStyle(fontSize: 18, color: Colors.red),
),
);
} else if (snapshot.hasData) {
final data = snapshot.data;
return Center(
child: Text(
data,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
);
}
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
),
),
));
}
}
Explanation
Let’s explain the code above:
- Lines 10–12: We defined the
getWriterNamefunction that returns a writer’sFuturename after three seconds of delay. It simulates an asynchronous operation using theFuture.delayedconstructor. - Lines 15–22: We defined the
buildmethod of a widget that returns aSafeAreawidget with aScaffoldas its child. The Scaffold contains anAppBarwidget with a purple accent background color and a centered title displayingFlutter FutureBuilder. - Lines 23–55: We define the body section of the
Scaffoldwidget; we use aSizedBoxandCenterwidget to contain aFutureBuilderthat monitors aFuture. TheFutureBuilderdisplays aCircularProgressIndicatorwhile theFutureis running and shows the result in aTextwidget if it completes successfully. If theFuturecompletes with an error, an error message is displayed in aTextwidget.
Free Resources