I have a problem. I created the following class:
enum WeatherType {
#JsonValue("sunny")
sunny,
#JsonValue("raining")
raining
}
class Location {
final String locationName;
final String adres;
final num? distance;
final num windSpeed;
final num windDirection;
final String windIconColor;
final num temperature;
final WeatherType weatherType;
TimeOfDay? arrivalTime;
Location(
{required this.locationName,
required this.adres,
required this.windSpeed,
required this.windDirection,
required this.temperature,
required this.weatherType,
required this.windIconColor,
this.distance});
Location.fromJson(Map<String, dynamic> json)
: locationName = json['locationName'],
adres = json['adres'],
distance = json['distance'],
windSpeed = json['windSpeed'],
windDirection = json['windDirection'],
windIconColor = json['windIconColor'],
temperature = json['temperature'],
weatherType = json['weatherType'],
arrivalTime =
TimeOfDay.fromDateTime(DateTime.parse(json['arrivalTime']));
Map<String, dynamic> toJson() {
return {
'locationName': locationName,
'adres': adres,
'distance': distance,
'windSpeed': windSpeed,
'windDirection': windDirection,
'windIconColor': windIconColor,
'temperature': temperature,
'weatherType': weatherType.toString(),
'arrivalTime': arrivalTime.toString(),
};
}
}
When I store this class as JSON string in the localstorage, it gets stored like this:
{"locationName":"Castricum aan Zee","adres":"Strand, 1901 NZ Castricum","distance":4,"windSpeed":12,"windDirection":90,"windIconColor":"76E648","temperature":5,"weatherType":"WeatherType.raining","arrivalTime":"TimeOfDay(23:20)"}
Then when I use the following line of code:
Location test = Location.fromJson(jsonDecode(json));
The app freezes when running that fromJson method. What am I doing wrong in the encoding/decoding of my class?
check for null in arrivalTime
From Json:
json['arrivalTime'] == null
? null
: DateTime.parse(json['arrivalTime'] as String),
To Json:
'arrivalTime': instance.reviewDate?.toIso8601String(),
Enum
enum WeatherType {
sunny,
raining
}
From JSON:
WeatherType deserializedWeatherType = WeatherType.values.byName(jsonValue);
To JSON:
String jsonValue = weatherType.name;
It's most likely because of the way you're decoding arrivalTime - When you encode arrival time, you encode it as a string: "TimeOfDay(23:20)". Then, when you decode it, you're using DateTime.parse(), which doesn't know how to parse that string.
To make your encoding compatible with your decoding, you can encode and decode the TimeOfDay in a more granular way:
Location.fromJson(Map<String, dynamic> json)
: locationName = json['locationName'],
adres = json['adres'],
distance = json['distance'],
windSpeed = json['windSpeed'],
windDirection = json['windDirection'],
windIconColor = json['windIconColor'],
temperature = json['temperature'],
weatherType = json['weatherType'],
arrivalTime = TimeOfDay(
hour: json['arrivalTime']['hour'],
minute: json['arrivalTime']['minute'],
);
Map<String, dynamic> toJson() {
return {
'locationName': locationName,
'adres': adres,
'distance': distance,
'windSpeed': windSpeed,
'windDirection': windDirection,
'windIconColor': windIconColor,
'temperature': temperature,
'weatherType': weatherType.toString(),
'arrivalTime': {
'hour': arrivalTime.hour,
'minute': arrivalTime.minute,
},
};
}
Related
Could anyone advise to read the JSON in Flutter as below:
{
"1":{
"title":"ករណី ANC",
"lists":[
{
"id":"1135",
"faci_code":"20103",
"y_txt":"2022",
"m_txt":"1",
"ind_id":"1",
"qty":"67",
"rec_by":"od1234",
"rec_date":"2022-03-02 13:53:58",
"lock_txt":"0",
"sec_id":"1",
"ind_num":"1.0",
"ind_eng":"# of ANC 1",
"ind_kh":"ចំនួនស្រ្ដីបានពិនិត្យផ្ទៃពោះលើកទី១ទាំងអស់",
"HFAC_NAME":"Rung Chrey",
"HFAC_NAMEKh":"រូងជ្រៃ",
"OD_CODE":"201",
"OD_NAME":"Thma Koul",
"OD_NAME_KH":"ថ្មគោល",
"PRO_CODE":"2",
"PROVINCE":"Battambang",
"PROVINCE_KH":"បាត់ដំបង"
},
{
"id":"1136",
"faci_code":"20103",
"y_txt":"2022",
"m_txt":"1",
"ind_id":"2",
"qty":"32",
"rec_by":"od1234",
"rec_date":"2022-03-02 13:53:58",
"lock_txt":"0",
"sec_id":"1",
"ind_num":"1.1",
"ind_eng":"# of ANC 2",
"ind_kh":"ចំនួនស្រ្ដីបានពិនិត្យផ្ទៃពោះលើកទី២ទាំងអស់",
"HFAC_NAME":"Rung Chrey",
"HFAC_NAMEKh":"រូងជ្រៃ",
"OD_CODE":"201",
"OD_NAME":"Thma Koul",
"OD_NAME_KH":"ថ្មគោល",
"PRO_CODE":"2",
"PROVINCE":"Battambang",
"PROVINCE_KH":"បាត់ដំបង"
}
]
}
}
Regard, thanks.
Vandet
import dart:convert;
And then
Map<String, dynamic> dataObject = jsonDecode(yourJsonData);
See the docs: https://docs.flutter.dev/development/data-and-backend/json
From my interpretation of your question, you either want to directly access the above json in Flutter OR you want to create models out of it.
In case you want to simply use the above Json in flutter, you can simply access its values using the keys. For example: assume the above json is stored in a variable jsonString and you want to print the first list and the first element of the lists under it -
print(jsonString["1"]);
print(jsonString["1"]["lists"][0]);
In case you want to create models out of the above json, you can either do it yourself by defining encompassing objects as separate classes and going around with it OR you can use some online tool to assist you in the same, like https://javiercbk.github.io/json_to_dart/, this will create an entire converion model for you from the sample json. In case of above json it would be like -
class Autogenerated {
One? one;
Autogenerated({this.one});
Autogenerated.fromJson(Map<String, dynamic> json) {
one = json['One'] != null ? new One.fromJson(json['One']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.one != null) {
data['One'] = this.one!.toJson();
}
return data;
}
}
class One {
String? title;
List<Lists>? lists;
One({this.title, this.lists});
One.fromJson(Map<String, dynamic> json) {
title = json['title'];
if (json['lists'] != null) {
lists = <Lists>[];
json['lists'].forEach((v) {
lists!.add(new Lists.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
if (this.lists != null) {
data['lists'] = this.lists!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Lists {
String? id;
String? faciCode;
String? yTxt;
String? mTxt;
String? indId;
String? qty;
String? recBy;
String? recDate;
String? lockTxt;
String? secId;
String? indNum;
String? indEng;
String? indKh;
String? hFACNAME;
String? hFACNAMEKh;
String? oDCODE;
String? oDNAME;
String? oDNAMEKH;
String? pROCODE;
String? pROVINCE;
String? pROVINCEKH;
Lists(
{this.id,
this.faciCode,
this.yTxt,
this.mTxt,
this.indId,
this.qty,
this.recBy,
this.recDate,
this.lockTxt,
this.secId,
this.indNum,
this.indEng,
this.indKh,
this.hFACNAME,
this.hFACNAMEKh,
this.oDCODE,
this.oDNAME,
this.oDNAMEKH,
this.pROCODE,
this.pROVINCE,
this.pROVINCEKH});
Lists.fromJson(Map<String, dynamic> json) {
id = json['id'];
faciCode = json['faci_code'];
yTxt = json['y_txt'];
mTxt = json['m_txt'];
indId = json['ind_id'];
qty = json['qty'];
recBy = json['rec_by'];
recDate = json['rec_date'];
lockTxt = json['lock_txt'];
secId = json['sec_id'];
indNum = json['ind_num'];
indEng = json['ind_eng'];
indKh = json['ind_kh'];
hFACNAME = json['HFAC_NAME'];
hFACNAMEKh = json['HFAC_NAMEKh'];
oDCODE = json['OD_CODE'];
oDNAME = json['OD_NAME'];
oDNAMEKH = json['OD_NAME_KH'];
pROCODE = json['PRO_CODE'];
pROVINCE = json['PROVINCE'];
pROVINCEKH = json['PROVINCE_KH'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['faci_code'] = this.faciCode;
data['y_txt'] = this.yTxt;
data['m_txt'] = this.mTxt;
data['ind_id'] = this.indId;
data['qty'] = this.qty;
data['rec_by'] = this.recBy;
data['rec_date'] = this.recDate;
data['lock_txt'] = this.lockTxt;
data['sec_id'] = this.secId;
data['ind_num'] = this.indNum;
data['ind_eng'] = this.indEng;
data['ind_kh'] = this.indKh;
data['HFAC_NAME'] = this.hFACNAME;
data['HFAC_NAMEKh'] = this.hFACNAMEKh;
data['OD_CODE'] = this.oDCODE;
data['OD_NAME'] = this.oDNAME;
data['OD_NAME_KH'] = this.oDNAMEKH;
data['PRO_CODE'] = this.pROCODE;
data['PROVINCE'] = this.pROVINCE;
data['PROVINCE_KH'] = this.pROVINCEKH;
return data;
}
}
NOTE: Avoid using numbers as json keys.
I was wondering if anyone could help, please? I'm very new to Flutter/Dart here and I'm trying to parse a nested JSON response, into a model. I've used the "JSON to Dart" generator, which seems to have worked well, except when it is parsing "responses".
I suspect the issue is because the "responses" vary in results - sometimes it could be null, a single array, or multiple.
Running .runtimeType has shown me that it can return null if it's empty, List<dynamic> if there is only one array, and _InternalLinkedHashMap<String, dynamic> when there are multiple.
I have tried many different approaches to try and resolve this and looked through many different StackOverflow answers, but nothing seems to work. The error simply changes with every change I make.
Below is my code and my error.
The error:
_TypeError (type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f')
The code:
class VideoComments {
int id;
String comment;
int uid;
int likes;
bool isLikedByUser;
String posterProfilePic;
String posterUsername;
List<Responses> responses;
VideoComments(
{this.id,
this.comment,
this.uid,
this.likes,
this.isLikedByUser,
this.posterProfilePic,
this.posterUsername,
this.responses});
VideoComments.fromJson(Map<String, dynamic> json) {
print("RESP: ${json['responses'].runtimeType}");
id = json['id'];
comment = json['comment'];
uid = json['uid'];
likes = json['likes'];
isLikedByUser = json['isLikedByUser'];
posterProfilePic = json['poster_profile_pic'];
posterUsername = json['poster_username'];
if (json['responses'] != null) {
List<Responses> responses = [];
json['responses'].forEach((v) {
responses.add(new Responses.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['comment'] = this.comment;
data['uid'] = this.uid;
data['likes'] = this.likes;
data['isLikedByUser'] = this.isLikedByUser;
data['poster_profile_pic'] = this.posterProfilePic;
data['poster_username'] = this.posterUsername;
if (this.responses != null) {
data['responses'] = this.responses.map((v) => v.toJson()).toList();
}
return data;
}
}
class Responses {
int id;
String comment;
int uid;
int likes;
bool isLikedByUser;
Responses({this.id, this.comment, this.uid, this.likes, this.isLikedByUser});
Responses.fromJson(Map<String, dynamic> json) {
id = json['id'];
comment = json['comment'];
uid = json['uid'];
likes = json['likes'];
isLikedByUser = json['isLikedByUser'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['comment'] = this.comment;
data['uid'] = this.uid;
data['likes'] = this.likes;
data['isLikedByUser'] = this.isLikedByUser;
return data;
}
}
Any help is appreciated!
Just for the fun of it - I tried to implement the same thing using json_serializable since I recommended it in my comment. Hopefully this shows you that it is not that complicated - in fact, it is simpler than actually figuring out how to code it your self.
First I started with the blank Flutter project.
Second, I added required dependencies to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
# Added this
json_annotation: ^4.0.1
dev_dependencies:
flutter_test:
sdk: flutter
# and these two...
build_runner: ^2.0.4
json_serializable: ^4.1.3
Next thing, I created a separate file json_demo.dart, and took part of your code. I also added few things:
part instruction that will include generated json mapping file
For each class added .fromJson named constructor
For each class added toJson() method.
Added #JsonSerializable() for each class - this is how the tool knows which class to look at
Added #JsonKey(name: 'poster_profile_pic') and #JsonKey(name: 'poster_username') - since your filed names are different than Json property names (poster_profile_pic vs posterProfilePic), you need to tell the tool how to rename it back and forth.
Made all properties nullable (since I'm using latest version with null-safety)
import 'package:json_annotation/json_annotation.dart';
part 'json_demo.g.dart';
#JsonSerializable()
class VideoComments {
int? id;
String? comment;
int? uid;
int? likes;
bool? isLikedByUser;
#JsonKey(name: 'poster_profile_pic')
String? posterProfilePic;
#JsonKey(name: 'poster_username')
String? posterUsername;
List<Responses>? responses;
VideoComments(
{this.id,
this.comment,
this.uid,
this.likes,
this.isLikedByUser,
this.posterProfilePic,
this.posterUsername,
this.responses});
factory VideoComments.fromJson(Map<String, dynamic> json) => _$VideoCommentsFromJson(json);
Map<String, dynamic> toJson() => _$VideoCommentsToJson(this);
}
#JsonSerializable()
class Responses {
int? id;
String? comment;
int? uid;
int? likes;
bool? isLikedByUser;
Responses({this.id, this.comment, this.uid, this.likes, this.isLikedByUser});
factory Responses.fromJson(Map<String, dynamic> json) => _$ResponsesFromJson(json);
Map<String, dynamic> toJson() => _$ResponsesToJson(this);
}
Now, simply run flutter pub run build_runner build, and you get json_demo.g.dart file generated:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'json_demo.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
VideoComments _$VideoCommentsFromJson(Map<String, dynamic> json) {
return VideoComments(
id: json['id'] as int?,
comment: json['comment'] as String?,
uid: json['uid'] as int?,
likes: json['likes'] as int?,
isLikedByUser: json['isLikedByUser'] as bool?,
posterProfilePic: json['poster_profile_pic'] as String?,
posterUsername: json['poster_username'] as String?,
responses: (json['responses'] as List<dynamic>?)
?.map((e) => Responses.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$VideoCommentsToJson(VideoComments instance) =>
<String, dynamic>{
'id': instance.id,
'comment': instance.comment,
'uid': instance.uid,
'likes': instance.likes,
'isLikedByUser': instance.isLikedByUser,
'poster_profile_pic': instance.posterProfilePic,
'poster_username': instance.posterUsername,
'responses': instance.responses,
};
Responses _$ResponsesFromJson(Map<String, dynamic> json) {
return Responses(
id: json['id'] as int?,
comment: json['comment'] as String?,
uid: json['uid'] as int?,
likes: json['likes'] as int?,
isLikedByUser: json['isLikedByUser'] as bool?,
);
}
Map<String, dynamic> _$ResponsesToJson(Responses instance) => <String, dynamic>{
'id': instance.id,
'comment': instance.comment,
'uid': instance.uid,
'likes': instance.likes,
'isLikedByUser': instance.isLikedByUser,
};
Note how it correctly renamed the json property based on the annotation:
posterProfilePic: json['poster_profile_pic'] as String?,
One more thing to notice - this is how it fixed the problem you had:
responses: (json['responses'] as List<dynamic>?)
?.map((e) => Responses.fromJson(e as Map<String, dynamic>))
.toList(),
From now on, each time you change your class, simple re-run the build script.
As you explore further, you'll see that it can handle enums, it has nice annotations to automatically rename all fields in a class from snake case to kebab case (or whatever it is called). But most importantly - does it in a consistent and tested way. As you add more classes, it will really help you save some time...
And to make your life easier, create user snippet in VS Code (File->Preferences->User snippets):
{
"Json Serializible": {
"prefix": "serial",
"body": [
"factory ${1}.fromJson(Map<String, dynamic> json) => _$${1}FromJson(json);",
"Map<String, dynamic> toJson() => _$${1}ToJson(this);"
]
}
}
Here's how to use it:
Copy the name of your class
start typing 'serial' - this is the shortcut for the code snippet
Select the snippet and paste the class name - it will paste it 3 times where needed.
See - simpler than learning how to manually encode/decode Json....
As #Andrija suggested, that is certainly a good way, if you don't want to use that then go ahead with the vscode extension bendixma.dart-data-class-generator, create your class and keep your variables, just do ctrl + shift + p -> Search data class, hit enter when you find dart data class generator from class properties.
Thank you everyone for your responses. I have no resolved the issue.
I have changed my code (in respect to the issue area) to the following:
if (json['responses'].length > 0) {
json['responses'].forEach((e) => responses.add(Responses.fromJson(e)));
} else if (json['responses'].length == 0 || json['responses'] == null) {
responses = null;
}
and on my web server, I have wrapped the "responses" in another (parent) array.
it is an error related to data type. Please cross the the JSON response and Dart class variable data type. String variable can't be an Int or Double value. Or do one thing change all variable into Dynamic type.
But yes it is not good practice to have dynamic as datatype for all variable.
I'm getting a Null check operator used on a null value error in flutter.
Map<String, dynamic> newUserMap = jsonDecode(authenticate.body);
print('newUserMap?');
var authNodeUser = TokenContent.fromJson(newUserMap);
print('authNodeUser?');
String? jwtToken = authNodeUser.jwtToken;
print('jwtToken = ' + authNodeUser.jwtToken!);
as I'm seeing newUserMap? and authNodeUser? I'm guessing the error occurs here;
String? jwtToken = authNodeUser.jwtToken;
print('jwtToken = ' + authNodeUser.jwtToken!);
Here's the TokenContent class;
class TokenContent {
int? currUser;
String? jwtToken;
String? refreshToken;
TokenContent({this.currUser, this.jwtToken, this.refreshToken});
TokenContent.fromJson(Map<String, dynamic> json) {
currUser = json['currUser'];
jwtToken = json['token'];
refreshToken = json['refreshToken'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['currUser'] = this.currUser;
data['jwtToken'] = this.jwtToken;
data['refreshToken'] = this.refreshToken;
return data;
}
}
How can I fix this?
Print newUserMap and make sure jwtToken exist in the http response.
I am working with an api as backend to fetch user data when logging in.
This is the code to get data:
Future<dynamic> getLoginData(String _phone, bool isPhone) async {
String endPoint = isPhone
? '/UserLogin_Mobile?PhoneNo=$_phone'
: '/UserLogin?Email=$_phone';
var response = await client
.get('$ENDPOINT' + endPoint, headers: headers)
.catchError((onError) {
print(onError.toString());
});
print("response=>" + response.body);
if (json.decode(response.body).toString().contains("registered"))
print("\n\nReg");
if (response.statusCode == 200) {
if (json.decode(response.body).toString().contains("not found"))
print("\n\nNot found");
return User.fromJson(jsonDecode(response.); //TODO getting error here
}
return null;
}
This is User model
class User {
double id;
String userPhone;
String userPass;
String userNicename;
String userEmail;
String userUrl;
String userRegistered;
String userActivationKey;
int userStatus;
String displayName;
String errorDis;
bool isSuccessfull = true;
String statuscode;
String message;
String latitude;
String longitude;
User(
{this.id,
this.userPhone,
this.userPass,
this.displayName,
this.userActivationKey,
this.userEmail,
this.userNicename,
this.userRegistered,
this.userStatus,
this.statuscode,
this.message,
this.userUrl});
User.initial()
: id = 0,
userPhone = '',
userPass = '',
userNicename = '',
userEmail = '',
userUrl = '',
statuscode = '',
userRegistered = '',
userActivationKey = '',
userStatus = 0,
displayName = '';
User.fromJson(Map<String, dynamic> json)
: id = json['ID'],
userPhone = json['user_login'],
userPass = json['user_pass'],
userNicename = json['user_nicename'],
userEmail = json['user_email'],
userUrl = json['user_url'],
userRegistered = json['user_registered'],
userActivationKey = json['user_activation_key'],
userStatus = json['user_status'],
displayName = json['display_name'],
statuscode = json['statuscode'],
message = json['message'],
latitude = json['latitude'],
longitude = json['longitude'];
User.errorFromServer(Map<String, dynamic> json) {
statuscode = json['statuscode'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['user_login'] = this.userPhone;
data['user_pass'] = this.userPass;
data['user_nicename'] = this.userNicename;
data['user_email'] = this.userEmail;
data['user_url'] = this.userEmail;
data['user_registered'] = this.userRegistered;
data['user_activation_key'] = this.userActivationKey;
data['user_status'] = this.userStatus;
data['display_name'] = this.displayName;
data['latitude'] = this.latitude;
data['longitude'] = this.longitude;
return data;
}
}
And this is the error being shown at TODO
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
I am getting this error because, at TODO, I am trying to map response.body (which is a string) to Map (that is user data).
How to solve it?? or is my question wrong?
EDIT
this is
response.body=> {"ID":633.0,"user_login":"xxxxxxxxxx","user_pass":"xxxxxx","user_nicename":"","user_email":"","user_url":"","user_registered":"0001-01-01T00:00:00","user_activation_key":"","user_status":0,"display_name":"","latitude":null,"longitude":null}
I`m using Dio package.
1, To parser response body to Model.
Check response.statusCode and to determined the model you need parse.
Use YourModel.fromJson(response.data) to parse, don't need jsonDecode
2, With Model, let use code generation (Json Model)
Sample:
import 'package:json_annotation/json_annotation.dart';
part 'sign_in_response.g.dart';
#JsonSerializable(
anyMap: true
)
class SignInResponse {
String accessToken;
String refreshToken;
SignInResponse(this.accessToken, this.refreshToken);
factory SignInResponse.fromJson(Map<String, dynamic> json) => _$SignInResponseFromJson(json);
Map<String, dynamic> toJson() => _$SignInResponseToJson(this);
}
Code gen:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'sign_in_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SignInResponse _$SignInResponseFromJson(Map json) {
return SignInResponse(
json['accessToken'] as String,
json['refreshToken'] as String,
);
}
Map<String, dynamic> _$SignInResponseToJson(SignInResponse instance) =>
<String, dynamic>{
'accessToken': instance.accessToken,
'refreshToken': instance.refreshToken,
};
i don't understand how parse json to list or any types in flutter
https://jsonplaceholder.typicode.com/photos <= this is json example what i use
and that info is surrounded by [], {}
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
List<Photo> simple =
parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
i expect when json.decode.cast() work, parsed contain each objects but
when i print parsed, it's just one array like [~~~]
why they use cast method with Map<>?
jsonDecode already gives you the list object, so you can optimize the code.
In your case , instead of using
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
List<Photo> simple =
parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
try using
final List<Photo> simple = jsonDecode(responseBody).map((item) => Photo(title: item.title)).toList()
and you avoid having a fromJson function
You do not need to cast the array because they are already a list of objects.
You can use the following to get a list of photo objects:
Future<String> getPhotos() async {
var response = await http.get(
'https://jsonplaceholder.typicode.com/photos');
if (response.statusCode == 200) {
var parsed = json.decode(response.body);
List<Photo> simple = parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
print(simple);
}
}
This is the photo class used.
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
Photo(
{this.albumId, this.id, this.title, this.url, this.thumbnailUrl});
factory Photo.fromJson(Map<dynamic, dynamic> json) {
return Photo(albumId: json['albumId'],
id: json['id'],
title: json['title'],
url: json['url'],
thumbnailUrl: json['thumbnailUrl'],
);
}
}