I want to show CircularProgressIndicator while waiting for future to resolve using flutter_riverpod, here is my code snippet.
But it’s not showing, I am using ConsumerStatefulWidget is this right way to do it?
ElevatedButton(
onPressed: () {
rejectResponse = ref
.read(notificationRepositoryProvider)
.approveDocument(1);
Navigator.of(context).pop();
setState(() {});
},
child: FutureBuilder(
future: rejectResponse,
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
if (snapshot.hasData) {
return Text('Yes');
} else if (snapshot.hasError) {
return Text('Error');
}
} else if (snapshot.connectionState ==
ConnectionState.waiting) {
return CircularProgressIndicator();
}
return Text('Yes');
}),
),
2
Answers
You can use
ConnectionState
, but I think it can also be innone
state. So you can check if its done, and if not, you should probably show the loading indicator anyway.I usually use the
hasData
property instead. This lets me reduce the number of states I have to deal with, and safely assumesnapshot.data
is notnull
. I use the below pattern.The preferred way of doing this in Riverpod is using a FutureProvider and AsyncValue:
Note that after the initial loading, the FutureProvider will return the previous value but will set AsyncValue.isRefreshing to true. To avoid this and always show the loader on refresh, you can set
skipLoadingOnRefresh
to false.