future builder flutter code example
Example 1: flutter future builder
FutureBuilder<String>(
future: _fetchNetworkCall, // async work
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return Text('Loading....');
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return Text('Result: ${snapshot.data}');
}
},
),
Example 2: future builder snapshot list
FutureBuilder(
future: _fetchListItems(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
Container(
child: ListView.builder(
itemCount: snapshot.data.length,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
return Text('${snapshot.data[index].title}');
}));
}
});
Example 3: flutter future builder
//The correct way to use FutureBuilder is to instantiate the future first,
//then use the variable in the FutureBuilder
//Check out: https://www.youtube.com/watch?v=LYN46233cws for more info
//Instantiate the future
Future _getData;
//In initState assign you future function to the future
@override
void initState() {
_getData = _getUserData();
super.initState();
}
//Define your async function
_getUserData() async{
return await getAsyncDataFromServer();
}
//Use the instantiated future variable in your future builder
FutureBuilder(
future: _getData;
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.connectionState == ConnectionState.done){
//Build you UI
}else{
return Center(child: CircularProgressIndicator());
}
},
);
Example 4: future builder flutter
Example of future function:Future getProjectDetails() async { List<ProjectModel> projetcList = await someFutureCall(); return projetcList; }
Example 5: future builder flutter
class ProjectModel { String id; String createdOn; String lastModifiedOn; String title; String description; ProjectModel({ this.id, this.createdOn, this.lastModifiedOn, this.title, this.description, });}