toJson method is throwing me an error on call - json

I may need help with this. Basically im getting this exception when calling order.toJson() method. I have been checking the code but seems good for me. If you see an error please let me know.
E/flutter ( 5623): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
Converting object to an encodable object failed: Instance of 'OrderItem'
E/flutter ( 5623): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter ( 5623): #1 _JsonStringifier.writeList (dart:convert/json.dart:736:7)
E/flutter ( 5623): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:718:7)
E/flutter ( 5623): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter ( 5623): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter ( 5623): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter ( 5623): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter ( 5623): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
When calling toJson() method. Here are my classes.
class Order{
String id;
String userId;
String deliverId;
String restaurantId;
List<OrderItem> orderItems;
double total;
String orderStatus;
Order({
required this.id,
required this.userId,
required this.deliverId,
required this.restaurantId,
required this.orderItems,
required this.total,
required this.orderStatus
});
Map<String, dynamic> toJson(){
return {
'id' : id,
'userId' : userId,
'deliverId' : deliverId,
'restaurantId' : restaurantId,
'orderItems' : jsonEncode(orderItems),
'total' : total,
'orderStatus' : orderStatus
};
}
}
OrderItem class
class OrderItem{
RestaurantModel restaurant;
List<OrderProduct> products;
String id;
OrderItem({
required this.restaurant,
required this.products,
required this.id
});
Map<String, dynamic> toJson(){
return {
'restaurant' : restaurant.toJson(),
'products' : jsonEncode(products),
'id' : id,
};
}
}
RestaurantModel class
class RestaurantModel {
String uid;
String restaurantName;
String restaurantAddress;
String restaurantUrl;
String restaurantSlogan;
int stars;
String cost;
String category;
String status;
DateTime startDate;
List<Product>? products;
RestaurantModel({
required this.uid,
required this.restaurantName,
required this.restaurantAddress,
required this.restaurantSlogan,
required this.restaurantUrl,
required this.stars,
required this.cost,
required this.category,
required this.status,
required this.startDate,
this.products,
});
Map<String, Object?> toJson(){
return{
'restaurantName' : restaurantName,
'restaurantAddress' : restaurantAddress,
'restaurantSlogan' : restaurantSlogan,
'restaurantUrl': restaurantUrl,
'stars' : stars,
'cost' : cost,
'category' : category,
'status' : status,
'startDate' : startDate,
};
}
}
OrderProduct class
class OrderProduct{
Product product;
int quantity;
OrderProduct({
required this.product,
required this.quantity,
});
Map<String, dynamic> toJson(){
return {
'product' : product.toJson(),
'quantity' : quantity,
};
}
}
Product class
class Product{
String productId;
String productName;
String productDescription;
double productPrice;
String productUrl;
int productLikes;
String productUnit;
Product({
required this.productId,
required this.productName,
required this.productDescription,
required this.productPrice,
required this.productUrl,
required this.productLikes,
required this.productUnit,
}
);
Map<String, dynamic> toJson(){
return {
'productId' : productId,
'productName' : productName,
'productDescription' : productDescription,
'productPrice' : productPrice,
'productUrl' : productUrl,
'productLikes' : productLikes,
'productUnit' : productUnit,
};
}
}
So basically I'm getting an error when trying to call toJson() method from order.
void addOrderAsync(String userId, Order order) async{
// here is where im getting the error
final jsonData = order.toJson();
final response = await http.post(Uri.parse("$apiUrl/users/$userId/cart/add"),
headers: <String, String> {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(jsonData),
);
if(response.statusCode == 200 || response.statusCode == 201){
// do something
}
else{
throw Exception("Failed to create user");
}
}

try change toJson() to:
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['productId'] = this.productId;
data['productName'] = this.productName;
data['productDescription'] = this.productDescription;
data['productPrice'] = this.productPrice;
data['productUrl'] = this.productUrl;
data['productLikes'] = this.productLikes;
data['productUnit'] = this.productUnit;
return data;
}

Try this:
Map<String, dynamic> toJson(){
return {
'id' : id,
'userId' : userId,
'deliverId' : deliverId,
'restaurantId' : restaurantId,
'orderItems' : orderItems.toJson(),
'total' : total,
'orderStatus' : orderStatus
};
}
Replace jsonEncode by toJson()

Related

Json serialization of nested objects dart

I am trying to generate fromJSON and toJson functions for my nested objects using the json_serializable library. But when I tried to use the generated functions, I got an error with deserialization of the nested object.
I think I understand how to write toJSON and FromJSON functions. But I want to figure out how to work with the json_serializable library and work with the generated code.
Class with models:
import 'package:json_annotation/json_annotation.dart';
part 'models.g.dart';
#JsonSerializable()
class OfficesList {
List<Office> offices;
OfficesList({required this.offices});
factory OfficesList.fromJson(Map<String, dynamic> json) => _$OfficesListFromJson(json);
Map<String, dynamic> toJson() => _$OfficesListToJson(this);
}
#JsonSerializable()
class Office {
final String name;
final String address;
final String image;
Office({required this.name, required this.address, required this.image});
factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
Map<String, dynamic> toJson() => _$OfficeToJson(this);
}
Generated class:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
OfficesList _$OfficesListFromJson(Map<String, dynamic> json) => OfficesList(
offices: (json['offices'] as List<dynamic>)
.map((e) => Office.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$OfficesListToJson(OfficesList instance) =>
<String, dynamic>{
'offices': instance.offices,
};
Office _$OfficeFromJson(Map<String, dynamic> json) => Office(
name: json['name'] as String,
address: json['address'] as String,
image: json['image'] as String,
);
Map<String, dynamic> _$OfficeToJson(Office instance) => <String, dynamic>{
'name': instance.name,
'address': instance.address,
'image': instance.image,
};
void main(){
Office of1 = Office(name: "pupa", address: "lupa", image: "image");
Office of2 = Office(name: "lupa", address: "pupa", image: "image");
OfficesList list1 = OfficesList(offices: [of1,of2]);
OfficesList list2 = OfficesList.fromJson(list1.toJson());
print(list2.toJson());
}
The exception in these lines
OfficesList list2 = OfficesList.fromJson(list1.toJson())
.map((e) => Office.fromJson(e as Map<String, dynamic>))
Unhandled exception:
type 'Office' is not a subtype of type 'Map<String, dynamic>' in type cast
#0 _$OfficesListFromJson.<anonymous closure> (package:jsom_test/models.g.dart:11:41)
#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#2 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#3 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27)
#4 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
#5 new List.of (dart:core-patch/array_patch.dart:51:28)
#6 ListIterable.toList (dart:_internal/iterable.dart:213:44)
#7 _$OfficesListFromJson (package:jsom_test/models.g.dart:12:12)
#8 new OfficesList.fromJson (package:jsom_test/models.dart:9:62)
#9 main (package:jsom_test/json_test.dart:9:35)
#10 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

dart update json serialization doesnt work the way i was used to

hi does anyone of you know how to parse a list of objects from a json string since everything has to be annotated?
i have the following code
import './utils.dart';
import 'dart:convert';
import 'package:hex/hex.dart';
import 'package:crypto/crypto.dart';
import 'dart:isolate';
import 'package:gladiators/models/constantes.dart';
class InterioreRationem {
final String publicaClavis;
BigInt nonce;
final String id;
InterioreRationem(this.publicaClavis, this.nonce): id = Utils.randomHex(32);
InterioreRationem.incipio(this.publicaClavis):
nonce = BigInt.zero,
id = Utils.randomHex(32);
mine() {
nonce += BigInt.one;
}
Map<String, dynamic> toJson() => {
'publicaClavis': publicaClavis,
'nonce': nonce.toString(),
'id': id
};
InterioreRationem.fromJson(Map<String, dynamic> jsoschon):
publicaClavis = jsoschon['publicaClavis'].toString(),
nonce = BigInt.parse(jsoschon['nonce'].toString()),
id = jsoschon['id'].toString();
}
class Propter {
late String probationem;
final InterioreRationem interioreRationem;
Propter(this.probationem, this.interioreRationem);
Propter.incipio(this.interioreRationem):
probationem = HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes);
static void quaestum(List<dynamic> argumentis) {
InterioreRationem interioreRationem = argumentis[0] as InterioreRationem;
SendPort mitte = argumentis[1] as SendPort;
String probationem = '';
int zeros = 1;
while (true) {
do {
interioreRationem.mine();
probationem = HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes);
} while(!probationem.startsWith('0' * zeros));
zeros += 1;
mitte.send(Propter(probationem, interioreRationem));
}
}
Map<String, dynamic> toJson() => {
'probationem': probationem,
'interioreRationem': interioreRationem.toJson()
};
Propter.fromJson(Map<String, dynamic> jsoschon):
probationem = jsoschon['probationem'].toString(),
interioreRationem = InterioreRationem.fromJson(jsoschon['interioreRationem'] as Map<String, dynamic>);
bool isProbationem() {
if (probationem == HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes)) {
return true;
}
return false;
}
}
class GladiatorInput {
final int index;
final String signature;
final String gladiatorId;
GladiatorInput(this.index, this.signature, this.gladiatorId);
Map<String, dynamic> toJson() => {
'index': index,
'signature': signature,
'gladiatorId': gladiatorId
};
GladiatorInput.fromJson(Map<String, dynamic> jsoschon):
index = int.parse(jsoschon['index'].toString()),
signature = jsoschon['signature'].toString(),
gladiatorId = jsoschon['gladiatorId'].toString();
}
class GladiatorOutput {
final List<Propter> rationem;
final String defensio;
GladiatorOutput(this.rationem): defensio = Utils.randomHex(1);
Map<String, dynamic> toJson() => {
'rationem': rationem.map((r) => r.toJson()).toList(),
'defensio': defensio
};
GladiatorOutput.fromJson(Map<String, dynamic> jsoschon):
rationem = List<Propter>.from(jsoschon['rationem'].map((r) => Propter.fromJson(r as Map<String, dynamic>)) as List<dynamic>),
defensio = jsoschon['defensio'].toString();
}
class Gladiator {
final GladiatorInput? input;
final List<GladiatorOutput> outputs;
final String random;
final String id;
Gladiator(this.input, this.outputs, this.random):
id = HEX.encode(
sha512.convert(
utf8.encode(json.encode(input?.toJson())) +
utf8.encode(json.encode(outputs.map((o) => o.toJson()).toList())) +
utf8.encode(random)).bytes);
Map<String, dynamic> toJson() => {
'input': input?.toJson(),
'outputs': outputs.map((o) => o.toJson()).toList(),
'random': random,
'id': id
};
Gladiator.fromJson(Map<String, dynamic> jsoschon):
input = jsoschon['input'] != null ? GladiatorInput.fromJson(jsoschon['input'] as Map<String, dynamic>) : null,
outputs = List<GladiatorOutput>.from(jsoschon['outputs'].map((o) => GladiatorOutput.fromJson(o as Map<String, dynamic>)) as List<dynamic>),
random = jsoschon['random'].toString(),
id = jsoschon['id'].toString();
static List<Propter> grab(int difficultas, List<Propter> propters) {
List<Propter> reditus = [];
for (int i = 64; i >= difficultas; i--) {
if(reditus.length < Constantes.perRationesObstructionum) {
reditus.addAll(propters.where((p) => p.probationem.startsWith('0' * difficultas) && !reditus.contains(p)));
} else {
break;
}
}
return reditus;
}
}
so i dont know how to convert a list of objects no more
i was jused to map it and call the fromjson method upon it but all of a sudden i have to annotate everything and i dont know whats the proper annotation for objects from a json string
does anyone know how to convert since the update?
i have the following error
-- Conduit CLI Version: 3.1.2
-- Conduit project version: 3.1.2
-- Starting application 'gladiators/gladiators'
Channel: GladiatorsChannel
Config: /home/noahbergh/gladiators/config.yaml
Port: 8888
[INFO] conduit: Server conduit/1 started.
#0 new Gladiator.fromJson (package:gladiators/models/gladiator.dart:112:128)
#1 new InterioreObstructionum.fromJson (package:gladiators/models/obstructionum.dart:214:29)
#2 new Obstructionum.fromJson (package:gladiators/models/obstructionum.dart:303:55)
#3 Utils.priorObstructionum (package:gladiators/models/utils.dart:38:21)
<asynchronous suspension>
#4 ObstructionumController.numerus (package:gladiators/controllers/obstructionum_controller.dart:13:27)
<asynchronous suspension>
#5 ResourceController._process (package:conduit/src/http/resource_controller.dart:363:22)
<asynchronous suspension>
#6 Controller.receive (package:conduit/src/http/controller.dart:162:24)
<asynchronous suspension>
[SEVERE] conduit: GET /obstructionum 95ms 500 {user-agent : Mozilla/5.0 (X11; CrOS x86_64 14588.123.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.72 Safari/537.36\nconnection : keep-alive\nsec-ch-ua-mobile : ?0\ncache-control : no-cache\nsec-fetch-dest : empty\npostman-token : dfb826a1-433b-db3b-5260-c65fe007fa93\naccept-encoding : gzip, deflate, br\nsec-fetch-site : none\naccept : */*\naccept-language : nl,en;q=0.9\nsec-fetch-mode : cors\nhost : localhost:8888\nsec-ch-ua-platform : "Chrome OS"\nsec-ch-ua : " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"\n} type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'List<dynamic>' in type cast #0 new Gladiator.fromJson (package:gladiators/models/gladiator.dart:112:128)
#1 new InterioreObstructionum.fromJson (package:gladiators/models/obstructionum.dart:214:29)
#2 new Obstructionum.fromJson (package:gladiators/models/obstructionum.dart:303:55)
#3 Utils.priorObstructionum (package:gladiators/models/utils.dart:38:21)
<asynchronous suspension>
#4 ObstructionumController.numerus (package:gladiators/controllers/obstructionum_controller.dart:13:27)
<asynchronous suspension>
#5 ResourceController._process (package:conduit/src/http/resource_controller.dart:363:22)
<asynchronous suspension>
#6 Controller.receive (package:conduit/src/http/controller.dart:162:24)
<asynchronous suspension>
^[[B^C-- Stopping application.
Reason: Process interrupted.

NoSuchMethodError : The method 'map' was called on null. Plz Provide the Solution

I am trying to parse data from a Rest API inside a Dart/Flutter application.
The JSON contains a field called data at the root, which contains a list of Words.
I want to get a List<ArticalList> from this JSON giving json["data"].map((x) => ArticalList.fromJson(x))
I already have the following code:
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.code,
required this.status,
required this.message,
required this.data,
});
final int code;
final String status;
final String message;
final List<ArticalList> data;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
code: json["code"] ?? 0,
status: json["status"] ?? '',
message: json["message"] ?? '',
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class ArticalList {
ArticalList({
required this.id,
required this.title,
required this.detail,
required this.image,
});
int id;
String title;
String detail;
String image;
factory ArticalList.fromJson(Map<String, dynamic> json) => ArticalList(
id: json["id"] == null ? 0 : json["id"],
title: json["title"] == null ? '' : json["title"],
detail: json["detail"] == null ? '' : json["detail"],
image: json["image"] ?? 'http://eduteksolutions.in/images/logo.jpeg',
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"detail": detail == null ? null : detail,
"image": image,
};
}
I think your getting error at
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
I create a function with null safety which accept map and return object list
static List<ArticalList> toListFormMap({
Map? map,
}) {
if (map?.isEmpty ?? true) return [];
List<ArticalList> items = [];
map?.forEach((key, data) {
final ArticalList item = ArticalList.fromJson(data);
items.add(item);
});
return items;
}
and same method which convert map to Map
static Map toMapList(List<ArticalList>? items) {
Map map = {};
items?.forEach((element) {
map[element.id] = element.toJson();
});
return map;
}
for both case it handle null data error and also convert Object List to Map list and Map list to Object list.
I hope it will be helpful.

cannot resolve type 'String' is not a subtype of type 'int' of 'index'

i started having an issue recently. I need to parse my json response to a list to my model object class but i keep getting this error:
type 'String' is not a subtype of type 'int' of 'index'
tried several solutions online but it didn't work for me. I was thing my variable declarations in my model class was the issue so i changed them to dynamic but didnt still work for me.
Heading
Model
class MenteeIndex {
dynamic id;
dynamic mentor_id;
dynamic mentee_id;
dynamic status;
dynamic session_count;
dynamic current_job;
dynamic email;
dynamic phone_call;
dynamic video_call;
dynamic face_to_face;
dynamic created_at;
dynamic updated_at;
MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);
Map<String, dynamic> toJson() => {
'id': id,
'mentor_id': mentor_id,
'mentee_id': mentee_id,
'status': status,
'session_count': session_count,
'current_job': current_job,
'email':email,
'phone_call': phone_call,
'video_call': video_call,
'face_to_face': face_to_face,
'created_at': created_at,
'updated_at': updated_at,
};
MenteeIndex.fromJson(Map<String, dynamic> json):
id = json['id'],
mentor_id = json['mentor_id'],
mentee_id = json['mentee_id'],
status = json['status'],
session_count = json['session_count'],
current_job = json['current_job'],
email = json['email'],
phone_call = json['phone_call'],
video_call = json['video_call'],
face_to_face = json['face_to_face'],
created_at = json['created_at'],
updated_at = json['updated_at'];
}
Main
Future fetchIndex() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host + AuthUtils.endPointIndex;
try {
final response = await http.get(
uri,
headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
);
var encodeFirst = json.encode(response.body);
final responseJson = json.decode(encodeFirst);
//here is where the error is
for (var u in responseJson["data"]) {
MenteeIndex user = MenteeIndex(
u["id"],
u["mentor_id"],
u["mentee_id"],
u["status"],
u["session_count"],
u["current_job"],
u["email"],
u["phone_call"],
u["video_call"],
u["face_to_face"],
u["created_at"],
u["updated_at"]);
menteeIndexes.add(user);
setState((){
mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
});
}
return responseJson;
} catch (exception) {
print(exception);
}
}
Response/Error
{"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'
Decode the response body to Map
final responseJson = json.decode(response.body);
Convert the Map list to MenteeIndex list
final menteeIndexes = responseJson["data"].map(
(json) => MenteeIndex.fromJson(json)
).toList();
Check out this model class
// To parse this JSON data, do
//
// final yourModel = yourModelFromJson(jsonString);
import 'dart:convert';
YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));
String yourModelToJson(YourModel data) => json.encode(data.toJson());
class YourModel {
int currentPage;
List<Datum> data;
YourModel({
this.currentPage,
this.data,
});
factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
currentPage: json["current_page"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"current_page": currentPage,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
String mentorId;
String menteeId;
dynamic status;
int sessionCount;
dynamic currentJob;
dynamic email;
dynamic phoneCall;
dynamic videoCall;
dynamic faceToFace;
DateTime createdAt;
DateTime updatedAt;
Datum({
this.id,
this.mentorId,
this.menteeId,
this.status,
this.sessionCount,
this.currentJob,
this.email,
this.phoneCall,
this.videoCall,
this.faceToFace,
this.createdAt,
this.updatedAt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
mentorId: json["mentor_id"],
menteeId: json["mentee_id"],
status: json["status"],
sessionCount: json["session_count"],
currentJob: json["current_job"],
email: json["email"],
phoneCall: json["phone_call"],
videoCall: json["video_call"],
faceToFace: json["face_to_face"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"mentor_id": mentorId,
"mentee_id": menteeId,
"status": status,
"session_count": sessionCount,
"current_job": currentJob,
"email": email,
"phone_call": phoneCall,
"video_call": videoCall,
"face_to_face": faceToFace,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Just insert you response.body to this method :
final yourModel = yourModelFromJson(response.body);
you can just get the list of data using below call :
List<Datum> dataList = List();
dataList = yourModel.data;
here you get the list of data
You will get your Single object from it and then depending on that you can do what ever you want.

(Resolved)(type 'String' is not a subtype of type 'int') - Flutter

This question has already been answered, continue reading if you think you have the same error, the answer was given by the user: Tariqul Islam
since a few days ago there was a flutter update my code shows the following error:
_TypeError (type 'String' is not a subtype of type 'int')
Obviously the application worked perfectly before this update, even after changing from "int" to "String" the same error I get but the other way around:
_TypeError (type 'int' is not a subtype of type 'String')
As much as I change the values ​​the same error still appears to me, it is also clear that the RestApi that I am using did not have any changes.
I get the error when I get to "Chip", after I change it to String I get the same error in "Number", and after I change both the same error appears but the other way around as I indicated above
Here the Json file model:
class EventoModel {
String id;
String nombreEvento;
List<Participantes> participantes;
EventoModel({
this.id,
this.nombreEvento,
this.participantes
});
factory EventoModel.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['participantes'] as List;
//print(list.runtimeType);
List<Participantes> participantesList = list.map((i) => Participantes.fromJson(i)).toList();
return EventoModel(
id : parsedJson ['id'],
nombreEvento : parsedJson ['nombreEvento'],
participantes : participantesList
);
}
}
class Participantes {
String uniqueId;
String apellido;
int chip;
String nombre;
int numero;
String place;
String tiempo;
Participantes({
this.apellido,
this.chip,
this.nombre,
this.numero,
this.place,
this.tiempo,
});
factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
//print(list.runtimeType);
return Participantes(
apellido : parsedJson['Apellido'],
chip : parsedJson['Chip'],
nombre : parsedJson['Nombre'],
numero : parsedJson['Numero'],
place : parsedJson['Place'],
tiempo : parsedJson['Tiempo'],
);
}
Map<String, dynamic> toJson() {
return {
'Apellido' : apellido,
'Chip' : chip,
'Nombre' : nombre,
'Numero' : numero,
'Place' : place,
'Tiempo' : tiempo,
};
}
}
This is the Json file Example:
{
"nombreEvento" : "Clasico El Colombiano 2020",
"participantes" : [ {
"Apellido" : "MARTINEZ GUTIERREZ",
"Chip" : "739",
"Nombre" : "JOSE",
"Numero" : "139",
"Place" : "1.",
"Tiempo" : "00:30:12,91"
}, {
"Apellido" : "SUAREZ MORERA",
"Chip" : "707",
"Nombre" : "DANIEL",
"Numero" : "107",
"Place" : "2.",
"Tiempo" : "02:00:17,54"
}, {
"Apellido" : "RODRIGUEZ VARGAS",
"Chip" : "1686",
"Nombre" : "JOSE LUIS",
"Numero" : "274",
"Place" : "3.",
"Tiempo" : "02:01:09,09"
}
]
}
Could someone please help me? : c
If the type of a variable is not explicitly specified, the variable’s type is dynamic. The dynamic keyword can also be used as a type annotation explicitly.
Instead of int you can use dynamic and it will solve the issue.
class Participantes {
String uniqueId;
String apellido;
dynamic chip;
String nombre;
dynamic numero;
String place;
String tiempo;
Participantes({
this.apellido,
this.chip,
this.nombre,
this.numero,
this.place,
this.tiempo,
});
I had like this issue and in this case I did defining type from int to dynamic then it solved. For example: In firebase side I defined number type and I read it with type of dynamic. If you do int in your codes it will warned you "type 'int' is not a subtype of type 'String'" but if you define dynamic it will solve.
Code sample is in below.
//class Survey
class Survey {
String name;
dynamic vote; // before it was int type and I have changed
DocumentReference reference;
Survey.fromMap(Map<String, dynamic> map, {this.reference})
//datanın var olup olmadığını kontrol et eğer varsa kullan
: assert(map["name"] != null),
assert(map["vote"] != null),
name = map["name"],
vote = map["vote"];
Anket.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data(), reference: snapshot.reference);
}
Just do int chip to String chip, and int numero to String numero because in your JSON data comes in String
class Participantes {
String uniqueId;
String apellido;
String chip;
String nombre;
String numero;
String place;
String tiempo;
Participantes({
this.apellido,
this.chip,
this.nombre,
this.numero,
this.place,
this.tiempo,
});
In Json you are receiving Chip and Numero as String but in your model file you are declaring as integer. change the datatype to String in your model file.
String numero;
String chip;
From the JSON you provided I have made a model class below:
check out and let me know:
// To parse this JSON data, do
//
// final eventoModel = eventoModelFromJson(jsonString);
import 'dart:convert';
EventoModel eventoModelFromJson(String str) => EventoModel.fromJson(json.decode(str));
String eventoModelToJson(EventoModel data) => json.encode(data.toJson());
class EventoModel {
String nombreEvento;
List<Participante> participantes;
EventoModel({
this.nombreEvento,
this.participantes,
});
factory EventoModel.fromJson(Map<String, dynamic> json) => EventoModel(
nombreEvento: json["nombreEvento"],
participantes: List<Participante>.from(json["participantes"].map((x) => Participante.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"nombreEvento": nombreEvento,
"participantes": List<dynamic>.from(participantes.map((x) => x.toJson())),
};
}
class Participante {
String apellido;
String chip;
String nombre;
String numero;
String place;
String tiempo;
Participante({
this.apellido,
this.chip,
this.nombre,
this.numero,
this.place,
this.tiempo,
});
factory Participante.fromJson(Map<String, dynamic> json) => Participante(
apellido: json["Apellido"],
chip: json["Chip"],
nombre: json["Nombre"],
numero: json["Numero"],
place: json["Place"],
tiempo: json["Tiempo"],
);
Map<String, dynamic> toJson() => {
"Apellido": apellido,
"Chip": chip,
"Nombre": nombre,
"Numero": numero,
"Place": place,
"Tiempo": tiempo,
};
}