Reputation: 185
My REST API built in NodeJs is hosted on Heroku. In my flutter app, to show a widget I need data from 7 routes which are interrelated. I am using http get to fetch data. The problem is, http get request is asynchronous and I need to fetch from multiple routes results 10-20 seconds to fetch. Here is my code snippet:
void initState() {
Future.delayed(Duration.zero).then((value) async {
setState(() {
_isLoading = true;
});
try {
await Provider.of<UserProvider>(context, listen: false).fetchAllUser();
await Provider.of<DoctorProfileProvider>(context, listen: false)
.fetchAllDoctor();
await Provider.of<CreatedAppointmentProvider>(context, listen: false)
.fetchAllCreatedAppointment();
await Provider.of<InstitutionProvider>(context, listen: false)
.fetchAllInstitution();
await Provider.of<ReviewProvider>(context, listen: false)
.fetchAllReview();
await Provider.of<ChamberProvider>(context, listen: false)
.fetchAllChamber();
await Provider.of<AvailableChamberProvider>(context, listen: false)
.fetchAllAvailableChamber();
} catch (err) {
throw err;
}
setState(() {
_isLoading = false;
});
});
super.initState();
}
How can I minimize the fetching time?
Upvotes: 1
Views: 1980
Reputation: 34270
Try requesting multiple API at the same time as below and update UI once result received:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
final urlList = ['http://google.com', 'http://apple.com'];
final responses = await Future.wait(
urlList.map((String url) {
return http.get(url);
}),
);
final List<dynamic> caches = responses.map((response) {
return json.decode(response.body);
}).toList();
}
Upvotes: 2