Home > Software engineering >  Replace "map" method to traditional loops in dart when fetching data from API
Replace "map" method to traditional loops in dart when fetching data from API

Time:06-19

I was wondering if there is a different approach more efficient to include data from a json API to a simple list. As I read in some posts, map method is the most time/resource consuming in comparation with the traditional for/while loop in Dart.

Currently I use this snippet to fetch my data:

Future<List<dynamic>> fetchData(url) async {
  var client = http.Client();
  final response = await client.get(Uri.parse(url));
  await Future.delayed(Duration(seconds:2));
  if (response.statusCode == 200) {
    var jsonDecoded = json.decode(response.body);
    BreedList = jsonDecoded.map((data) => DogClass.fromJson(data)).toList();
    glossarList = BreedList;
    return BreedList;
  } else {
    throw Exception('Failed to load data');
  }
}

I tried this approach:

Future<List<dynamic>> fetchDataFor(url) async {
  var client = http.Client();
  final response = await client.get(Uri.parse(url));
  await Future.delayed(Duration(seconds:2));
  if (response.statusCode == 200) {
    var jsonDecoded = json.decode(response.body);
    for (var k in jsonDecoded.keys){
      BreedList.add({jsonDecoded[k]});
    }
    return BreedList;
  } else {
    throw Exception('Failed to load data');
  }
}

But it returns the error: Class List has no instance getter 'keys'.

So, what would be the equivalent for the "map" method ?

CodePudding user response:

You can use collection-for to perform a straightforward transformation of .map calls.

var result = iterable.map((element) => transform(element)).toList();

can be replaced with:

var result = [for (var element in iterable) transform(element)];

So in your case:

BreedList = jsonDecoded.map((data) => DogClass.fromJson(data)).toList();

can become:

BreedList = [for (var data in jsonDecoded) DogClass.fromJson(data)];
  • Related