Am getting this error in flutter, dart.
‘_InternalLinkedHashMap<String, dynamic>’ is not a subtype of type
‘List’
The Model used is,
import 'dart:convert';
Areas areasFromJson(String str) => Areas.fromJson(json.decode(str));
String areasToJson(Areas data) => json.encode(data.toJson());
class Areas {
bool success;
Data data;
String message;
Areas({
required this.success,
required this.data,
required this.message,
});
factory Areas.fromJson(Map<String, dynamic> json) => Areas(
success: json["success"],
data: Data.fromJson(json["data"]),
message: json["message"],
);
Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
"message": message,
};
}
class Data {
List<Area> areas;
Data({
required this.areas,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
areas: List<Area>.from(json["areas"].map((x) => Area.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"areas": List<dynamic>.from(areas.map((x) => x.toJson())),
};
}
class Area {
int id;
String name;
String state;
String country;
DateTime createdAt;
DateTime updatedAt;
Area({
required this.id,
required this.name,
required this.state,
required this.country,
required this.createdAt,
required this.updatedAt,
});
factory Area.fromJson(Map<String, dynamic> json) => Area(
id: json["id"],
name: json["name"],
state: json["state"],
country: json["country"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"state": state,
"country": country,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
In the controller file, trying to call the GET API via override init @override
void initState() {
getAreas();
super.initState(); }
Future<List<Areas>> getAreas() async {
final Map<String, String> headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
};
final response = await http.get(Uri.parse('https://idonor.ae/api/get-areas'),
headers: headers);
if (response.statusCode == 200) {
final List result = json.decode(response.body);
print(result);
final String responseString = response.body;
final Areas getAreas = Areas.fromJson(json.decode(responseString));
print(getAreas.data.areas);
return result.map((e) => Areas.fromJson(e)).toList();
} else {
throw Exception('Failed to load data');
}
}
I just looking to get the data and show in text data when the page loads.
3
Answers
excuse me.
this is json object json.decode(response.body); not List
delete to this lines
You already have the function to get area from json string
areasFromJson
.If you believe that the
response.body
isString
type, simply passresponse.body
toareasFromJson
, otherwise convert it to json string usingjson.encode(response.body))
.Example:
If you are trying to assign a map to a list, use the List.from constructor to create a list from the map values.
For example: