Widget with a futurebuilder
import 'package:flutter/material.dart';
class FuturebuilderTest extends StatelessWidget {
String data;
Future myFuture() async {
data = "External";
await Future.delayed(Duration(seconds: 2));
/* If we return data from the future, the snapshot will recieve data
return "This is snapshot data";
*/
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(20),
child: FutureBuilder(
future: myFuture(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
{
if (snapshot.hasData) {
return Text('Done(snapshot=${snapshot.data})');
} else if (snapshot.hasError) {
return Text('Future error');
} else {
return Text('Done(no-snapshot, data=$data)');
}
}
break;
case ConnectionState.waiting:
{
return Center(
child: CircularProgressIndicator(),
);
}
break;
default:
{
return Text('Undefined');
}
}
}),
),
);
}
}Multiple futures in a futurebuilder (Using Future.wait method)
FutureBuilder(
future: Future.wait([
context.read<Searching>().getSomeData1(),
context.read<Searching>().getSomeData2(),
]),
builder: (context, AsyncSnapshot<List<dynamic>> dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
if (dataSnapshot.hasError) {
return Center(
child: Text('Future error: ${dataSnapshot.error}'),
);
} else {
print(dataSnapshot.data![0]);
print(dataSnapshot.data![1]);
return Text('OK');
}
}
},
),