Reputation: 17
I am wondering if there are faster ways of doing this fetch, the for loop currently takes approx 10s but it's waiting for each fetch to finish before starting on the next one I also tried a forEach loop but then I had issues with the responses array being empty. Is there any smart Dart way of fetching it faster then returning the array to flamingotest
Here is my code!
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../classes/flamingo_test.dart';
import '../classes/convert_wallet.dart' as walletfunc;
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import '../utilities/assets.dart' as assets; // Object of assets
Future<FlamingoTest> fetchPost() async {
String apiUrl = "xxxxxx";
var responses = [];
for (var mapEntry in assets.assets.entries) {
var wallet = Settings.getValue<String>("user-wallet", "");
print(wallet);
var userWalletSeed = walletfunc.convertWallet(wallet);
print(userWalletSeed);
var body = json.encode({
"jsonrpc": "2.0",
"method": "invokefunction",
"params": [
"4d92194e8d73980dadbadfc1993b2014c9fbd9da",
"checkFLM",
[
{"type": "Hash160", "value": userWalletSeed},
{"type": "Hash160", "value": mapEntry.value}
]
],
"id": 3
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
var response =
await http.post(Uri.parse(apiUrl), body: body, headers: headers);
print(response);
if (response.statusCode == 200) {
print(response);
var uncoded = jsonDecode(response.body);
responses.add(uncoded);
} else {
throw Exception('Failed to load post');
}
}
return new FlamingoTest.fromJson(responses);
}
Upvotes: 1
Views: 1220
Reputation: 2020
You can use Future.wait
like this. The map
will return a Iterable of Future<Response>
and perform the post simultaneously.
Future<Response> fetchResponse(var mapEntryValue) async {
//The code in your for-loop goes here
...
return response;
}
Future<FlamingoTest> fetchPost() async {
var responses = [];
await Future.wait(
assets.assets.entries
.map<Future<Response>>(
(MapEntry me) => fetchResponse(me.value),
)
.toList(),
).then((listOfResponses) {
responses.addAll(listOfResponses);
});
return new FlamingoTest.fromJson(responses);
}
Upvotes: 2