Flutter
List model
Produce List<Model> from a JSON array.
Turning a JSON array into List<Model>
To turn a JSON array into a List<Model>, first decode it into a List with jsonDecode, then pass each element through the model's fromJson constructor with .map(). Since .map() returns an Iterable, you need to call .toList() at the end.
const s = '[{"ad":"Ali"},{"ad":"Veli"}]';
final liste = jsonDecode(s) as List;
final kullanicilar = liste
.map((e) => Kullanici.fromJson(e as Map<String, dynamic>))
.toList();
print(kullanicilar.length); // 2
Iterable and toList
jsonDecode returns a JSON array as a List<dynamic>; element types are dynamic. Inside .map() you cast each e to Map<String, dynamic> and pass it to fromJson. Without .toList() the result is an Iterable and cannot be used as a list.
final liste = jsonDecode(s) as List;
final sonuc = liste
.map((e) => Kullanici.fromJson(e as Map<String, dynamic>))
.toList(); // Iterable to List
sonuc.forEach((k) => print(k.ad));
Exercise Convert a JSON array to models
Decode the string s with jsonDecode and cast it to List. Convert each element to a model with Kullanici.fromJson and turn the result into a list with .toList(). Print the length of the list with print.
Show example solution
import 'dart:convert';
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
factory Kullanici.fromJson(Map<String, dynamic> json) {
return Kullanici(json['ad'] as String, json['yas'] as int);
}
}
void main() {
const s = '[{"ad":"Ali","yas":20},{"ad":"Veli","yas":25}]';
final liste = jsonDecode(s) as List;
final kullanicilar = liste
.map((e) => Kullanici.fromJson(e as Map<String, dynamic>))
.toList();
print(kullanicilar.length);
}
Test yourself
-
Which approach correctly converts a JSON array to a list of models?
- Call liste.forEach((e) => Kullanici.fromJson(e))
- Call jsonEncode(liste)
- Call liste.cast<Kullanici>()
- Call liste.map((e) => Kullanici.fromJson(e as Map<String, dynamic>)).toList()
Show answer
Call liste.map((e) => Kullanici.fromJson(e as Map<String, dynamic>)).toList() — jsonEncode serializes the list, doesn't convert to models. cast throws at runtime because elements are Maps. forEach returns void and the result can't be assigned. The correct way is .map((e) => fromJson(e)).toList().
-
Convert Iterable to List
final liste = jsonDecode(s) as List;
final kullanicilar = liste
.map((e) => Kullanici.fromJson(e as Map<String, dynamic>))
____;
print(kullanicilar.length);
Show answer
final liste = jsonDecode(s) as List;
final kullanicilar = liste
.map((e) => Kullanici.fromJson(e as Map<String, dynamic>))
.toList();
print(kullanicilar.length);
-
List conversion parts
- .map((e) => ...)
- Transforms each element
- .toList()
- Converts Iterable to List
- e as Map<String, dynamic>
- Casts element to Map
- List<Kullanici>
- Result type
Next lesson: Summary - Model classes