How to get items with json if all keys are unique? - json

I have Json uploaded on a conditional server, I access this server via Dio:
Future getDataDio() async {
try {
final Dio dio = Dio();
final response = await dio
.get('https://run.mocky.io/v3/26681b8c-6581-4b8b-8fbe-3da2dc7bb785');
return HystoryOperations.fromJson(response.data);
} on DioError catch (e) {
print('error log: ${e.error}');
}
}
Json example I'm referring to:
{
"transaction_556505":{
"date" : "14.01.2022 г.",
"time" : "00:52",
"sum" : 351.05,
"id_order" : 556505,
"status_order" : "paid",
"type_order" : "payment_in"
},
"transaction_556329":{
"date" : "14.01.2022 г.",
"time" : "00:59",
"sum" : 1222.96,
"id_order" : 556329,
"status_order" : "payment_not_completed",
"type_order" : "payment_in"
},
"transaction_555111":{
"date" : "13.01.2022 г.",
"time" : "15:11",
"sum" : 512.71,
"id_order" : 555111,
"status_order" : "in_processing",
"type_order" : "payment_in"
}
}
Json serialization has been written, in which an exception appears due to the fact that all keys in the Json request are unique:
#JsonSerializable(explicitToJson: true)
class HystoryOperations {
final Map<String, dynamic> transaction;
HystoryOperations({required this.transaction});
factory HystoryOperations.fromJson(Map<String, dynamic> json) =>
_$HystoryOperationsFromJson(json);
Map<String, dynamic> toJson() => _$HystoryOperationsToJson(this);
}
// GENERATED CODE
HystoryOperations _$HystoryOperationsFromJson(Map<String, dynamic> json) =>
HystoryOperations(
transaction: json['transaction'] as Map<String, dynamic>, //Exception has occurred. _CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast)
);
Map<String, dynamic> _$HystoryOperationsToJson(HystoryOperations instance) =>
<String, dynamic>{
'transaction': instance.transaction,
};

Its easy.
You have to make two model classes.
One for List of Transactions and one for Individual transactions.
Then you can easily Get all the items from this type of JSON.
Your first Model Class should look like:
class Transactions{
String transaction = "";
List listOfTransactionNames = [];
List <IndividualTransactions> listOfTransaction = [];
Transactions.empty();
Transactions.fromJson(Map<String,dynamic> json){
listOfTransactionNames.addAll(json.keys);
for(int i = 0; i<json.length;i++){
listOfTransaction.add(
IndividualTransactions.fromJson(json[listOfTransactionNames[i]]));
}
}
}
And Your second Model Class looks like this.
class IndividualTransactions {
String date = "14.01.2022 г.";
String time = "00:52";
double sum = 351.05;
int id_order = 556505;
String status_order = "paid";
String type_order = "payment_in";
IndividualTransactions.fromJson(Map<String, dynamic> json) {
date = json["date"];
time = json["time"];
sum = json["sum"];
id_order = json["id_order"];
status_order = json["status_order"];
type_order = json["type_order"];
}
}
What happening here is :-
We are adding all keys inside a List of String named as "listOfTransactionNames " and then finding all Individual Transactions using those keys.
After that we are using from Json method of second class to add all single values in the list of "listOfTransaction" which are found by keys inside "listOfTransactionNames".

Thanks #Prashant
Fixed the JSON request:
[
{
"date" : "14.01.2022 г.",
"time" : "00:52",
"sum" : 351.05,
"id_order" : 556505,
"status_order" : "paid",
"type_order" : "payment_in"
},
{
"date" : "14.01.2022 г.",
"time" : "00:59",
"sum" : 1222.96,
"id_order" : 556329,
"status_order" : "payment_not_completed",
"type_order" : "payment_in"
},
{
"date" : "13.01.2022 г.",
"time" : "15:11",
"sum" : 512.71,
"id_order" : 555111,
"status_order" : "in_processing",
"type_order" : "payment_in"
},
{
"date" : "13.01.2022 г.",
"time" : "09:32",
"sum" : 351.05,
"id_order" : 556506,
"status_order" : "paid",
"type_order" : "refund_money"
}
]
and serialization with access to JSON via dio:
#JsonSerializable(explicitToJson: true)
class HystoryOperationsModel {
final String date;
final String time;
final double sum;
#JsonKey(name: 'id_order')
final int idOrder;
#JsonKey(name: 'status_order')
final String statusOrder;
#JsonKey(name: 'type_order')
final String typeOrder;
HystoryOperationsModel({
required this.date,
required this.time,
required this.sum,
required this.idOrder,
required this.statusOrder,
required this.typeOrder,
});
factory HystoryOperationsModel.fromJson(Map<String, dynamic> json) =>
_$HystoryOperationsModelFromJson(json);
Map<String, dynamic> toJson() => _$HystoryOperationsModelToJson(this);
}
Future<dynamic> getDataDioHistory = Future<dynamic>.delayed(
const Duration(seconds: 1),
() async {
final Dio dio = Dio();
try {
final response = await dio
.get('https://run.mocky.io/v3/b8fa7c11-8ae7-46f1-b783-6b7a2d44bc1c');
return response.data
.map<HystoryOperationsModel>(
(e) => HystoryOperationsModel.fromJson(e))
.toList();
} on DioError catch (e) {
print('error log: ${e.error}');
}
},
);

Related

Firebase nested HttpsCallableResult to dart model

I'm trying to get some data from a cloud function and assign it to a model. But I am unable to used the nested data, I get the following error:
_TypeError (type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>')
The data I receive looks like this:
{
"answer": "Some optional answer",
"error": "Some optional error",
"usage": { "prompt_tokens": 32, "completion_tokens": 40, "total_tokens": 72 }
}
When I receive the data I try to assign it to a model:
final HttpsCallableResult result = await functions
.httpsCallable('askHW')
.call({'question': userQuestion});
return HWResponse.fromJson(result.data);
HWResoponse:
class HWResponse {
final String answer;
final String error;
final HWUsage usage;
HWResponse({this.answer = '', this.error = '', required this.usage});
factory HWResponse.fromJson(Map<String, dynamic> json) => HWResponse(
answer: json.containsKey('answer') ? json['answer'] as String : '',
error: json.containsKey('error') ? json['error'] as String : '',
usage:
json["usage"] == null ? HWUsage() : HWUsage.fromJson(json["usage"]),
);
Map<String, dynamic> toJson() => {
"answer": answer,
"error": error,
"usage": usage.toJson(),
};
}
class HWUsage {
final int promptTokens;
final int completionTokens;
final int totalTokens;
HWUsage({
this.promptTokens = 0,
this.completionTokens = 0,
this.totalTokens = 0,
});
factory HWUsage.fromJson(Map<String, dynamic> json) => HWUsage(
promptTokens: json.containsKey('prompt_tokens')
? json['prompt_tokens'] as int
: 0,
completionTokens: json.containsKey('completion_tokens')
? json['completion_tokens'] as int
: 0,
totalTokens:
json.containsKey('total_tokens') ? json['total_tokens'] as int : 0,
);
Map<String, dynamic> toJson() => {
"prompt_tokens": promptTokens,
"completion_tokens": completionTokens,
"total_tokens": totalTokens,
};
}
Using Map<String, dynamic>.from('json['usage]') in HWResponse on the nested field seems to be the correct way to do this. To avoid any errors I also used json.containsKey('usage') to make sure that the nested field usage actually exists.
usage: json.containsKey('usage')
? HWUsage.fromJson(Map<String, dynamic>.from(json['usage']))
: HWUsage(),

Error To show Data Parsed Json In Flutter

I Have One Http Post Method Like This :
class ApiClientController extends GetxController {
Future<GetSideMenuInfoError?> GetInfoAfterLogin() async {
String? value = await storage.read(key: 'skey');
try {
final response = await dio.post(
Constant.baseUrl,
options: Options(
headers: {
"omax-apikey": "apikey",
},
),
data: {
"function": "portal_get_information",
"params": {
"portal_version": "1.0.0",
"portal_os": "linux",
"portal_os_version": "10",
"portal_browser": "chrome",
"portal_guid": "fd298776-6014-11ed-adbc-5256454165"
}
},
);
//print(response.data.toString());
GetSideMenuInfoError? responseBody = getSideMenuInfoErrorFromJson(response.data.toString());
return responseBody;
} on DioError catch (e) {
//return ;
print(e);
}
return null;
//IMPLEMENT USER LOGIN
}
}
And The Result Post Method My Json :
{
"result": 55456465,
"data": {
"reason": "session expired or not valid",
"uuid": "01dfca14-625559-11ed-aafa-0056546546"
}
}
Used This https://app.quicktype.io/ for Parsed Json To dart File Result Like This:
import 'package:meta/meta.dart';
import 'dart:convert';
GetSideMenuInfoError? getSideMenuInfoErrorFromJson(String str) => GetSideMenuInfoError?.fromJson(json.decode(str));
class GetSideMenuInfoError {
GetSideMenuInfoError({
#required this.result,
#required this.data,
});
final int? result;
final Data? data;
factory GetSideMenuInfoError.fromJson(Map<String, dynamic> json) => GetSideMenuInfoError(
result: json["result"],
data: Data.fromJson(json["data"]),
);
}
class Data {
Data({
#required this.reason,
#required this.uuid,
});
final String? reason;
final String? uuid;
factory Data.fromJson(Map<String, dynamic> json) => Data(
reason: json["reason"],
uuid: json["uuid"],
);
}
And My Question Is : How Can I Show value in Dart File Like reason or uuid In Other Class ?
My Way like This in Other Class And Not Worked:
In The Build Widget :
final apiClientController = Get.find<ApiClientController>();
apiClientController.GetInfoAfterLogin();
GetSideMenuInfoError? getSideMenuInfoError;
title: getSideMenuInfoError != null ?
Text(getSideMenuInfoError.result.toString()):Text('',),
Thank You For Helping Me...

How To access data in a list but inside the list has nested maps

Hello Im trying to get data from the Jasonplaceholder Api, and I want to map it in a dart model
but I tried videos on YouTube and none of them work and I use autogenerated models but the data that received are inside a list but in that list have nested maps
var myMap=[{
"name" : "Ravindu",
"age" : 20,
"scl" : "smc",
"address" :
{
"city" : "Kegalle",
"country" : "sri lanka"
}
},
{
"name" : "Ravindu1",
"age" : 20,
"scl" : "smc1",
"address" :
{
"city" : "Kegalle1",
"country" : "sri lanka1"
}
}];
like this I want this to map to a Molde class and also, I want to know how to access Items inside this map tried myMap[0]["address"] but it only retrieve the whole map of address in the 0 index
so How can I pass these type of Json data to a model class
this is the actual url im working with
'''final String url ="https://jsonplaceholder.typicode.com/users"'''
I get this error when I try this on darpad
Uncaught Error: TypeError: Instance of 'JsLinkedHashMap<String, String>': type 'JsLinkedHashMap<String, String>' is not a subtype of type 'List'
this is the code I tried on dartpad
void main() {
var myMap=[{
"name" : "Ravindu",
"age" : 20,
"scl" : "smc",
"address" :
{
"city" : "Kegalle",
"country" : "sri lanka"
}
},
{
"name" : "Ravindu1",
"age" : 20,
"scl" : "smc1",
"address" :
{
"city" : "Kegalle1",
"country" : "sri lanka1"
}
}];
print(myMap[0]);
var addressList = myMap[0]["address"]["city"];
print(addressList);
(addressList as List).forEach((i){
print(i["country"]);
});
}
The addressList will get from myMap[0]["address"] which will be another map. On Map, forEach callback provide key and value .forEach((key, value) {
void main() {
List<Map<String, dynamic>> myMap = [
{
"name": "Ravindu",
"age": 20,
"scl": "smc",
"address": {"city": "Kegalle", "country": "sri lanka"}
},
{
"name": "Ravindu1",
"age": 20,
"scl": "smc1",
"address": {"city": "Kegalle1", "country": "sri lanka1"}
}
];
print(myMap[0].toString());
final addressList = myMap[0]["address"]["city"];
print(addressList.toString()); // kegalle
final Map<String, String> address = myMap[0]["address"];
address.forEach((key, value) {
print(" $key $value");
});
}
I am also using Dart class generator extion
class Person {
final String? name;
final int? age;
final String? scl;
final Address? address;
Person({
this.name,
this.age,
this.scl,
this.address,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(name != null){
result.addAll({'name': name});
}
if(age != null){
result.addAll({'age': age});
}
if(scl != null){
result.addAll({'scl': scl});
}
if(address != null){
result.addAll({'address': address!.toMap()});
}
return result;
}
factory Person.fromMap(Map<String, dynamic> map) {
return Person(
name: map['name'],
age: map['age']?.toInt(),
scl: map['scl'],
address: map['address'] != null ? Address.fromMap(map['address']) : null,
);
}
String toJson() => json.encode(toMap());
factory Person.fromJson(String source) => Person.fromMap(json.decode(source));
}
class Address {
final String? city;
final String? country;
Address({
this.city,
this.country,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(city != null){
result.addAll({'city': city});
}
if(country != null){
result.addAll({'country': country});
}
return result;
}
factory Address.fromMap(Map<String, dynamic> map) {
return Address(
city: map['city'],
country: map['country'],
);
}
String toJson() => json.encode(toMap());
factory Address.fromJson(String source) => Address.fromMap(json.decode(source));
}
try to get the json structure with this model.
First of all be sure to have json_annotation and http as a normal dependency, and json_serializable, build_runner as a dev dependencies.
Example of pubspec.yaml:
dependencies:
json_annotation: ^4.7.0
# used for HTTP calls
http: ^0.13.5
# other dependencies
dev_dependencies:
build_runner: ^2.3.2
json_serializable: ^6.5.4
# other dependencies
Then you should create a model with the fromJson method. This is going to be used to deserialize the JSON you retrieve from the API call. I'm going to use a Dart file named user.dart
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
#JsonSerializable()
class User {
const User({
required this.id,
required this.name,
required this.username,
required this.email,
required this.address,
});
final int id;
final String name;
final String username;
final String email;
final Address address;
/// Connect the generated [_$UserFromJson] function to the `fromJson`
/// factory.
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// Connect the generated [_$UserToJson] function to the `toJson` method.
Map<String, dynamic> toJson() => _$UserToJson(this);
}
#JsonSerializable()
class Address {
const Address({
required this.city,
required this.street,
required this.zipcode,
});
final String city;
final String street;
final String zipcode;
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
Now in your Terminal you should run flutter pub run build_runner build --delete-conflicting-outputs to build the generated file, in my case it will generate a file called user.g.dart.
Now you need a service to make the HTTP call and return the list of users, I'm going to create a file called users_service.dart
import 'dart:convert';
import 'package:stackoverflow/user.dart';
import 'package:http/http.dart' as http;
class UsersService {
Future<List<User>> getUsers() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/users');
final response = await http.get(uri);
final responseString = response.body;
final jsonList = List.from(jsonDecode(responseString));
return jsonList.map((json) => User.fromJson(json)).toList();
}
}
Here you must focus on the jsonDecode method that converts the JSON to a Dart object, and in the User.fromJson method that deserializes the JSON object converting it into a valid User Dart class.
As you can see the address field is another class with its fromJson implementation.
This is the right way to perform JSON (de)serialization, because it doesn't involve doing it manually (more error prone)
Example usage:
import 'package:stackoverflow/users_service.dart';
Future<void> main() async {
final users = await UsersService().getUsers();
for (final user in users) {
print("${user.name} lives in ${user.address.city}");
}
}
which prints:
Leanne Graham lives in Gwenborough
Ervin Howell lives in Wisokyburgh
Clementine Bauch lives in McKenziehaven
Patricia Lebsack lives in South Elvis
Chelsey Dietrich lives in Roscoeview
Mrs. Dennis Schulist lives in South Christy
Kurtis Weissnat lives in Howemouth
Nicholas Runolfsdottir V lives in Aliyaview
Glenna Reichert lives in Bartholomebury
Clementina DuBuque lives in Lebsackbury

Problem with fetch: '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

I'm trying to fetch data from an API, but I keep getting this error.
Problem with fetch: '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
Please tell me how to fix this code.
Model.dart
class ComprovanteModel {
ComprovantesInfoModel jsonResponse;
String error;
ComprovanteModel({this.jsonResponse, this.error});
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response']),
error = '';
ComprovanteModel.withError(String errorValue)
: jsonResponse = null,
error = errorValue;
}
class ComprovanteInfoModel {
String clientFormalName;
int volumes;
int duration;
CheckpointsModel checkpoint;
ComprovanteInfoModel({
this.clientFormalName,
this.duration,
this.volumes,
this.checkpoint,
});
ComprovanteInfoModel.fromJson(Map<String, dynamic> json)
: clientFormalName = json['client_formal_name'],
checkpoint = CheckpointsModel.fromJson(json['checkpoint']),
volumes = json['volumes'],
duration = json['duration'];
}
class CheckpointModel {
int checkpointId;
String arrivalTime;
int status;
CheckpointModel({
this.checkpointId,
this.arrivalTime,
this.status,
});
CheckpointModel.fromJson(Map<String, dynamic> json)
: checkpointId = json['checkpoint_id'],
arrivalTime = json['arrival_time'],
status = json['status'];
}
class CheckpointsModel {
List<CheckpointModel> checkpoint;
CheckpointsModel({this.checkpoint});
CheckpointsModel.fromJson(List<dynamic> jsonList)
: checkpoint = jsonList.map((e) => CheckpointModel.fromJson(e)).toList();
}
The API response:
{
"json_response": [
{
"client_formal_name": "",
"deadline": null,
"volumes": 1,
"duration": 5,
"depot_id": 20,
"service_id": 109856,
"georef_provider": "ap_geocoder",
"checkpoint": {
"checkpoint_id":,
"arrival_time": "",
"duration":,
"status": 1,
"event_id": 5,
"resources": [
{
"content_type": "PHOTO",
"service_event_effect_id": 58,
"content": "em+ndG6XtE2unp",
"content_label": "",
"user_effect_unique_code": ""
},
{
"content_type": "RECEPTOR_INFO",
"service_event_effect_id": 61,
"content": "{\"user_relationship_unique_code\":\"\",\"is_expected_receiver\":\"true\",\"document\":\"65979973000240\",\"name\":\"",\"description\":\"",\"id\":\"1\"}",
"content_label": "",
"user_effect_unique_code": "2"
}
],
"event_description": "",
"operation_date": "",
"obs": "",
"is_assistant": false,
"image": "{\"description\": \"Documento\", \"photo\": \""}"
},
"final_attendance_window_b": null
}
]
}
I want to access the checkpoint item, then the resource item(which I think is the same process as the checkpoint). I am using the list but I don't think is right, I am suppose to use map but I don't know how. Please show me a way.
Change this:
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response']),
error = '';
To this:
ComprovanteModel.fromJson(Map<String, dynamic> json)
: jsonResponse = ComprovantesInfoModel.fromJson(json['json_response'][0]), //added [0] here.
error = '';
If you look closely at your response, it does have the map that you need, but this map is actually inside a list, notice the square brackets [ ] around the {} in "json_response": [.
The map that you need to access, is at index[0] of this list, then everything will work fine.
Second thing, this:
CheckpointsModel.fromJson(List<dynamic> jsonList)
: checkpoint = jsonList.map((e) => CheckpointModel.fromJson(e)).toList();
}
You are telling Flutter that you will pass an object of type List<dynamic> , but in the json you post, "checkpoint": { is not a list, it's a map. But even so, this map has only one checkpoint.
To answer your last question
I wanna access the checkpoint item, then the resource item(wich i
think is the same process as the checkpoint).
"resources": [ is indeed a list of Maps. In your code you did not post your resources model, but I'm assuming you want a List<Resources> and not List<CheckPoint>, it'll look like this:
class SingleResourceModel {
String contentType;
int serviceId;
String content;
String contentLabel;
String uniqueCode;
SingleResourceModel({
this.contentType,
this.serviceId,
this.content,
this.contentLabel,
this.uniqueCode
});
SingleResourceModel.fromJson(Map<String, dynamic> json)
: contentType = json['content_type'],
serviceId = json['service_event_effect_id'],
content = json['content'];
contentLabel = json['content_label'],
uniqueCode = json['user_effect_unique_code'];
}
class ListResourceModel {
List<SingleResourceModel> resourcesList;
ListResourceModel({this.resourcesList});
ListResourceModel.fromJson(List<Map<String, dynamic>> jsonList)
: resourcesList = jsonList.map((e) => SingleResourceModel.fromJson(e)).toList();
}
Finally, you can modify your CheckPoint model, and add to it a ListResourceModel, to look like this in the end:
class CheckpointModel {
int checkpointId;
String arrivalTime;
int status;
ListResourceModel resourcesList;
CheckpointModel({
this.checkpointId,
this.arrivalTime,
this.status,
this.resourcesList
});
CheckpointModel.fromJson(Map<String, dynamic> json)
: checkpointId = json['checkpoint_id'],
arrivalTime = json['arrival_time'],
status = json['status'],
resourcesList= json['resources'];
}
Now, you should be all set.

(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,
};
}