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);
}
}