I try to get data from api. CallListDto class is empty according to user type. So, sometime this class is empty sometimes it has data. I populate dropdown menu items with this class.
My problem is, when this class is empty i got error. How can i solve this.
My model class is below
Login loginFromJson(String str) => Login.fromJson(json.decode(str));
String loginToJson(Login data) => json.encode(data.toJson());
class Login {
Login({
required this.token,
required this.callListDto,
});
String token;
List<CallListDto> callListDto;
factory Login.fromJson(Map<String, dynamic> json) => Login(
token: json["token"],
callListDto: List<CallListDto>.from(
json["callListDto"].map((x) => CallListDto.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"token": token,
"callListDto": List<dynamic>.from(callListDto.map((x) => x.toJson())),
};
}
class CallListDto {
CallListDto({
required this.callId,
required this.stationCode,
required this.callType,
});
int callId;
String stationCode;
int callType;
factory CallListDto.fromJson(Map<String, dynamic> json) => CallListDto(
callId: json["callID"],
stationCode: json["stationCode"],
callType: json["callType"],
);
Map<String, dynamic> toJson() => {
"callID": callId,
"stationCode": stationCode,
"callType": callType,
};
}
Before calling the model class check that str is not empty, for example
if (dataObject.isEmpty) return;
Related
I used the fromJson method to recover a Struct with a List from Json decode http request and receiver it on my class, but now i want to do a reverse, i want to pass the data on my class to my toJson method and send him to a Json encode http POST. Please, i new on Dart/Flutter, someone know how to do this?
import 'dart:convert';
List<Itens> userFromJson(String str) =>
List<Itens>.from(jsonDecode(str).map((x) => Itens.fromJson(x)));
class Coletas {
final int codigo;
final String dataIni;
late String? dataFin;
late String? status;
final List<Itens> itemList;
Coletas(
{
required this.dataIni,
this.dataFin,
this.status,
required this.codigo,
required this.itemList
}
);
factory Coletas.fromJson(Map<String, dynamic> json) {
return Coletas(
dataIni: json['dtData'],
codigo: json['iCodigo'],
itemList: List<Itens>.from(json['stItens'].map((x) => Itens.fromJson(x))),
);
}
Map<String, dynamic> toMap() {
return {
'codigo': codigo,
'dataIni': dataIni,
'dataFin': dataFin,
'status': status
};
}
}
class Itens {
final int? id;
final int codigo;
late int quantidade;
late String? status;
final String codigoEAN;
Itens({
this.id,
this.status,
required this.codigo,
required this.codigoEAN,
required this.quantidade,
});
Map<String, dynamic> toJson(){
return {
'icodigo' : codigo,
'sCodigoBarras': codigoEAN,
'iQtd': quantidade
};
}
factory Itens.fromJson(Map<String, dynamic> json) {
return Itens(
codigo: json['iCodigo'],
codigoEAN: json['sCodigoBarras'],
quantidade: json['iQtd'],
);
}
Map<String, dynamic> toMap() {
return {
'id': id,
'status': status,
'codigo': codigo,
'codigoEAN': codigoEAN,
'quantidade': quantidade,
};
}
}
I tried to pass ever item on List separeted so, but not happen i expected.
Map<String, dynamic> toJSon(Coletas value) =>
{
'dtData' : dataIni,
'iCodigo': codigo,
'stItens': [],
};
For a better structure - format and use you can look at the flutter serialization documentation : https://docs.flutter.dev/development/data-and-backend/json.
It explains how to create your model and how to generate them to create fromJson and toJson Model based on the defined data. (https://docs.flutter.dev/development/data-and-backend/json#creating-model-classes-the-json_serializable-way)
It will helps you with your parsing - sending - receiving data.
I think you should assign Coletas as
Map<String, dynamic> toJSon(Coletas value) =>
{
'dtData' : value.dataIni,
'iCodigo': value.codigo,
'stItens': value.itemList,
};
I am new to flutter and I am learning APIs. My API model has a list named result. Can you please tell me how can I display that list and all other variables inside it by using snapshot.data
I am trying to declare
snapshot.data!.result but it is not working. Please give me the solution to this problem
Model code is below
class LeaguesModel {
LeaguesModel({
required this.success,
required this.result,
});
int success;
List<Result> result;
factory LeaguesModel.fromJson(Map<String, dynamic> json) => LeaguesModel(
success: json["success"],
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"result": List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.leagueKey,
required this.leagueName,
required this.countryKey,
required this.countryName,
required this.leagueLogo,
required this.countryLogo,
});
String leagueKey;
String leagueName;
String countryKey;
String countryName;
String leagueLogo;
String countryLogo;
factory Result.fromJson(Map<String, dynamic> json) => Result(
leagueKey: json["league_key"],
leagueName: json["league_name"],
countryKey: json["country_key"],
countryName: json["country_name"],
leagueLogo: json["league_logo"],
countryLogo: json["country_logo"],
);
Map<String, dynamic> toJson() => {
"league_key": leagueKey,
"league_name": leagueName,
"country_key": countryKey,
"country_name": countryName,
"league_logo": leagueLogo,
"country_logo": countryLogo,
};
static List<Result> jsontoApiModel(List<dynamic> emote) => emote.map<Result>((item) => Result.fromJson(item)).toList();
}
I am trying to convert a list of objects as a json string in shared preferences.
Object class
SuggestionModel suggestionModelFromJson(String str) =>
SuggestionModel.fromJson(json.decode(str));
String suggestionModelToJson(SuggestionModel data) =>
json.encode(data.toJson());
class SuggestionModel {
SuggestionModel({
this.category,
this.icon,
this.subs,
});
eCategory? category;
IconData? icon;
List<Sub>? subs;
factory SuggestionModel.fromJson(Map<String, dynamic> json) =>
SuggestionModel(
category: json["category"],
icon: json["icon"],
subs: List<Sub>.from(json["subs"].map((x) => Sub.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"icon": icon,
"subs": List<dynamic>.from(subs!.map((x) => x.toJson())),
};
}
class Sub {
Sub({
this.subCategory,
this.values,
});
String? subCategory;
List<Value>? values;
factory Sub.fromJson(Map<String, dynamic> json) => Sub(
subCategory: json["sub_category"],
values: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sub_category": subCategory,
"values": List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
class Value {
Value({
this.subName,
this.selected,
});
String? subName;
bool? selected;
factory Value.fromJson(Map<String, dynamic> json) => Value(
subName: json["sub_name"],
selected: json["selected"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"selected": selected,
};
}
When I try to do
List<SuggestionModel> list;
String encodedData = jsonEncode(list);
it gives me an error
Converting object to an encodable object failed: Instance of 'SuggestionModel'
Im not following where the exact issue comes from. tried debugging and still no luck
How can I rectify this?
Update. I've changed the enum to a String and removed the IconData field. And the above issue had resolved.
Now when I try to get the saved Json string and convert that back to list of objects. I get an error
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<SuggestionModel>'
at this line
var t = await _dataManager.getSelectedList(s);
var addedObj = json.decode(json.decode(t!));
//here...
var list = addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
Try this:
String encodedData = jsonEncode(list.map((e) => e.toJson()).toList());
So the first thing was to update the enum property of Model class to String and remove IconData.
Then for the second issue.
update the decoding function like
List<SuggestionModel> list =
addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
In my flutter app , I have 5 parameters for a building Like eleveator,storeroom,parking,buildAge,rentPriceThe default value of these parameters is 0 at the beginning ,I want to update every value in this ApartemanRentOptionModel class in different steps without changing other values and finally send complete values to the server.
I have a class for Rent Apartemans Options Like This :
class ApartemanRentOptionModel {
ApartemanRentOptionModel({
this.eleveator,
this.storeroom,
this.parking,
this.buildAge,
this.rentPrice
});
bool eleveator;
bool storeroom;
bool parking;
List<BuildAge> buildAge;
List<RentPrice> rentPrice;
factory ApartemanRentOptionModel.fromJson(Map<String, dynamic> json) => ApartemanRentOptionModel(
eleveator: json["eleveator"],
storeroom: json["storeroom"],
parking: json["parking"],
buildAge: List<BuildAge>.from(json["buildAge"].map((x) => BuildAge.fromJson(x))),
rentPrice: List<RentPrice>.from(json["rentPrice"].map((x) => RentPrice.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"eleveator": eleveator,
"storeroom": storeroom,
"parking": parking,
"buildAge": List<dynamic>.from(buildAge.map((x) => x.toJson())),
"rentPrice": List<dynamic>.from(rentPrice.map((x) => x.toJson())),
};
}
class BuildAge {
BuildAge({
this.buildAgeId,
this.buildAgeTitle,
this.buildAgeValue,
});
String buildAgeId;
String buildAgeTitle;
int buildAgeValue;
factory BuildAge.fromJson(Map<String, dynamic> json) => BuildAge(
buildAgeId: json["buildAgeID"],
buildAgeTitle: json["buildAgeTitle"],
buildAgeValue: json["buildAgeValue"],
);
Map<String, dynamic> toJson() => {
"buildAgeID": buildAgeId,
"buildAgeTitle": buildAgeTitle,
"buildAgeValue": buildAgeValue,
};
}
class RentPrice {
RentPrice({
this.rentPriceId,
this.rentPriceTitle,
this.rentPriceValue,
});
String rentPriceId;
String rentPriceTitle;
double rentPriceValue;
factory RentPrice.fromJson(Map<String, dynamic> json) => RentPrice(
rentPriceId: json["rentPriceID"],
rentPriceTitle: json["rentPriceTitle"],
rentPriceValue: json["rentPriceValue"].toDouble(),
);
Map<String, dynamic> toJson() => {
"rentPriceID": rentPriceId,
"rentPriceTitle": rentPriceTitle,
"rentPriceValue": rentPriceValue,
};
}
i need to change value in some data like BuildAge or RentPrice with a function like this :
ApartemanRentOptionModel _currentApartemanData;
changeCurretAparemanData(newdata) {
_currentApartemanData.toJson().update("BuildAge", (value) => newdata)
notifyListeners();
return null;
}
But it not work and nothing changes , Please help me how to update different values of a single Model class in several time . Thank you
You can use getter or setter function in model .getter function use for get value from model and setter use for set or update value in model.
I have the following two classes where one is extending from the other like this :
#JsonSerializable(nullable: true)
class Response {
final String responseCode;
final String responseMessage;
final String errorLog;
Response({this.errorLog, this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
.........................................................
#JsonSerializable(nullable: false)
class Verify extends Response {
Data data;
Verify({
this.data,
});
factory Verify.fromJson(Map<String, dynamic> json) => _$VerifyFromJson(json);
Map<String, dynamic> toJson() => _$VerifyToJson(this);
}
and whenever I'm trying to read response class properties from Verify class, it's always null.
so please how to achieve this?
this one I have solved by passing the parameters to super in verify class constructor like this
#JsonSerializable()
class VerifyResponse extends Response {
Data data;
VerifyResponse({
this.data,
String responseCode,
String responseMessage,
}) : super(responseCode: responseCode, responseMessage: responseMessage);
factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
_$VerifyResponseFromJson(json);
Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
}
and for the response class it remains the same
#JsonSerializable()
class Response {
final String responseCode;
final String responseMessage;
Response({this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
it's a bit annoying but it's what it's.
You should remove 'final' keyword from Response Class
#JsonSerializable(nullable: true)
class Response {
String responseCode;
String responseMessage;
String errorLog;
Response({this.errorLog, this.responseCode, this.responseMessage});
factory Response.fromJson(Map<String, dynamic> json) =>
_$ResponseFromJson(json);
}
It worked by adding super(); explicitly to the child class's constructor.
#JsonSerializable()
class VerifyResponse extends Response {
Data data;
VerifyResponse({
this.data,
String responseCode,
String responseMessage,
//No need to list all parent class properties
}) : super();
factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
_$VerifyResponseFromJson(json);
Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
}