How to fetch multiple JSON endpoints in async manner, then get results at end?

1,018 views
Skip to first unread message

dimi...@gmail.com

unread,
Feb 27, 2019, 10:26:33 PM2/27/19
to Flutter Dev

I am struggling with isolates and Futures.


All I want is iterating through a list of urls, which will return JSON arrays of anything.

And then funnelling all JSON array items into my own list of items in an async way.

I am not sure how to proceed, but it seems _fetchAndParse() is not constructed properly (expecting future), and I am at the end of the stick :)


Flutter docs examples are fetching on main thread, and then moving to parse and return data in a separate isolate via compute().

I am trying to fetch and parse in a separate isolate.

Any advice is welcome.



import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
 
@override
 
Widget build(BuildContext context) {
 _getJson
();

 
return MaterialApp(
 title
: 'Flutter Demo',
 home
: Text('Hello'));
 
}

 
Future<List<dynamic>> _getJson() async {
 
final List<String> urls = [
 
'https://api.github.com/users/mralexgray/repos',
 
'https://api.github.com/users/mralexgray/repos',
 
'https://api.github.com/users/mralexgray/repos'
 
];
 
final List<dynamic> result = [];

 urls
.forEach((url) async {
 await compute
(_fetchAndParse, url).then((items) => result.addAll(items));
 
});

 
return result;
 
}

 
List<dynamic> _fetchAndParse(String url) {
 
var client = http.Client();
 
final response = client.get(url);
 
return json.decode(response.body);
 
}
}


Matthew Jones

unread,
Feb 28, 2019, 12:43:16 PM2/28/19
to Flutter Dev
Have you taken a look at the BLOC pattern? I think this might help you. 

You need to create a stream. Each of your JSON responses would be dumped into the stream's sink. You could then handle the stream's output as it becomes available. 

Dart's implementation of streams isn't perfect, but the RxDart library helps a lot with it. 

Good luck!
Reply all
Reply to author
Forward
0 new messages