I'm trying to figure out a way to indicate to a surrounding class when the FutureBuilder
is done loading. RefreshIndicator
takes a Future
as a parameter and stops showing the refresh indicator when the Future
completes. I don't have access to the exact same Future
variable that's being passed to the FutureBuilder
, especially when these are in two separate classes, unless I can pass a reference to one and when it completes in the other class, I'll know...
I'm searching for this answer too. Finally i figured it out...
Here is how i done
FutureBuilder<String>(
future: _calculation,
// a previously-obtained Future<String> or null
builder: (BuildContext context,
AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return new RefreshIndicator(
key: _refreshIndicatorKey,
color: Colors.blue,
onRefresh: () {
return _calculation = getCalculation(); // EDITED
},
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Text('Result: ${snapshot.data}')
)
);
break;
default:
return null;
}
},
)
Future<String> getCalculation() async {
try {
/*Write your API here or what ever u want to get when pull to refresh*/
return ""/*the value of api*/; //EDITED
} catch (e) {
///Handle Exception here. So in FutureBuilder we can capture it in snapshot.hasError
return Future.error(e.toString());
}
}
You have to access the snapshot, provided builder
parm:
So, snapshot.data gives you the Future.
new FutureBuilder<String>(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
Example: https://flutter.io/cookbook/networking/background-parsing/
Doc: https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With