2

I would like to do the unit test for model by Flutter. Then I want to use test json data.

But I got the error message.
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

I want to know how to solve this issue.

Here is the test codes.

void main() {
  group('Gift Test', () {
    test('Gift model test', () {
      final file = File('json/gift_test.json').readAsStringSync();
      final gifts = Gift.fromJson(jsonDecode(file) as Map<String, dynamic>);

      expect(gifts.id, 999);
    });
  });
}

Here is the model

@freezed
abstract class Gift with _$Gift {
  @Implements(BaseModel)
  const factory Gift({
    int id,
    String name,
    int amount,
    Image image,
  }) = _Gift;

  factory Gift.fromJson(Map<String, dynamic> json) => _$GiftFromJson(json);
}

And this is the test data.

[
  {
    "id": 999,
    "name": "testest",
    "amount": 30000,
    "image": {
      "id": 9999,
      "image": {
        "url": "https://text.jpg",
      },
    },
  }
]
1
  • The problem is that in the json file you have a List so dart is inferring it is a List<dymanic> you can either remove the [] from the /gift_test.json, or iterate over it and do a test over each one item. Commented Apr 14, 2022 at 13:54

1 Answer 1

1

Your json file is a list, not an object, either you change your json file in

  {
    "id": 999,
    "name": "testest",
    "amount": 30000,
    "image": {
      "id": 9999,
      "image": {
        "url": "https://text.jpg",
      },
    },
  }

Or you will need to update your code to take the first element of the list:

final file = File('json/gift_test.json').readAsStringSync();
final gifts = Gift.fromJson((jsonDecode(file) as List).first as Map<String, dynamic>);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. It works! Why do I have to cast the List?
Your Json file has its object inside a list (your file starts with [ and ends with ]). So when you decode it, you get a List and you need to cast it to be able to use .first on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.