How to create List of object after parsing json in dart

179 Views Asked by At

This is how I am parsing my JSON, It's working but I want to know how would I create an instance of List<Result> to access the data inside it in my widgets. Help, please!

class Test {
  Test({
    required this.results,
  });

  List<Result> results;

  factory Test.fromJson(Map<String, dynamic> json) => Test(
        results:
            (json["results"] as List).map((e) => Result.fromJson(e)).toList(),
      );
}

Test testFromJson(String str) => Test.fromJson(json.decode(str));

Secondly, when I use this code in the section below instead of the last line of code in the above section, I get the following type error, please tell me what exactly this error means.

_TypeError (type '(dynamic) => Test' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')

List<Test> modelFromJson(String str) =>
List<Test>.from(json.decode(str).map((x) => Test.fromJson(x)));
1

There are 1 best solutions below

1
Семён Плевако On

Solution

factory Test.fromJson(Map<String, dynamic> json) => Test(
    results: (json["results"] as List).map((e) => Result.fromJson(e as Map<String, dynamic>)).toList(),
  );

The best solution - https://docs.flutter.dev/development/data-and-backend/json