user2570135
user2570135

Reputation: 2989

How to resolve dart error --Exception has occurred. _TypeError (type 'List<dynamic>' is not a subtype of type 'String')

I am getting the following error in Dart..

Exception has occurred. _TypeError (type 'List' is not a subtype of type 'String')

This is my code,,

class Hits {
 String incentives;
 Hits({
   this.incentives,
 });

Hits.fromJson(Map<String, dynamic> json) {
   incentives = json['incentives'];
}

}

The value in the JSON has 1 of the following value

0:"incentives" -> List (1 item)
   key:"incentives"
   value:List (1 item)
   [0]:""
   String:""

OR

0:"incentives" -> null
key:"incentives"
value:null

Can you give me a hit on how to resolve this error..

Thanks

Upvotes: 0

Views: 345

Answers (1)

lrn
lrn

Reputation: 71713

The code provided here describes the problem precisely.

The json map has a property named "incentives" which is a list (List<dynamic>) with one element. You try to assign this value to the field incentives which has type String.

Since a List<dynamic> is not assignable to String, that fails.

It fails at runtime because the static type of json['incentives'] is dynamic, so the compiler cannot determine at compile-time that the value is not assignable to String. As the type error states: "type 'List' is not a subtype of type 'String'".

I'm not sure how to solve the problem, because it's not clear which value you actually want to assign to incentives. Maybe all you need is to change the type of the incentives field to List<dynamic>. That depends on how the class will be used.

Upvotes: 1

Related Questions