Flutter How to parse Api response? - json

Im working with rawg.io api and trying to get datas about games. There is a problem which i think it's about parsing data from json. I worked with easy apis which has not arrays or maps in it. But this data complicated and i guess that's why im getting always null results while try to print datas to screen.
Here is my code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:video_games/load_data.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Future<Welcome> apiCall() async {
final response = await http.get(Uri.parse(
'https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56'));
print(response.statusCode);
print(response.body);
return Welcome.fromJson(jsonDecode(response.body));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder<Welcome>(
future: apiCall(),
builder: (context, snapshot) {
// var growableList = [];
// List<Result> data = snapshot.data!.results;
// growableList.add(data[0].name);
return Text('${snapshot.data!.count}');
},
),
),
);
}
}
That is my response body and status code without using in a widget or parsing it
I/flutter ( 3666): 200
I/flutter ( 3666): {"count":679153,"next":"https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56&page=2","previous":null,"results":[{"id":3498,"slug":"grand-theft-auto-v","name":"Grand Theft Auto V","released":"2013-09-17","tba":false,"background_image":"https://media.rawg.io/media/games/456/456dea5e1c7e3cd07060c14e96612001.jpg","rating":4.48,"rating_top":5,"ratings":[{"id":5,"title":"exceptional","count":3217,"percent":58.97},{"id":4,"title":"recommended","count":1800,"percent":33.0},{"id":3,"title":"meh","count":348,"percent":6.38},{"id":1,"title":"skip","count":90,"percent":1.65}],"ratings_count":5389,"reviews_text_count":36,"added":16689,"added_by_status":{"yet":415,"owned":9874,"beaten":4491,"toplay":474,"dropped":835,"playing":600},"metacritic":97,"playtime":71,"suggestions_count":402,"updated":"2021-08-20T12:42:02","user_game":null,"reviews_count":5455,"saturated_color":"0f0f0f","dominant_color":"0f0f0f","platforms":[{"platform":{"id":1,"name":"Xbox One","slug":"xbox-one","image":null,"year_end":null,"year_
And this is my data class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
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.count,
required this.next,
required this.previous,
required this.results,
});
int count;
String next;
String previous;
List<Result> results;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
count: json["count"],
next: json["next"],
previous: json["previous"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"count": count,
"next": next,
"previous": previous,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.slug,
required this.name,
required this.released,
required this.tba,
required this.backgroundImage,
required this.rating,
required this.ratingTop,
required this.ratings,
required this.ratingsCount,
required this.reviewsTextCount,
required this.added,
required this.addedByStatus,
required this.metacritic,
required this.playtime,
required this.suggestionsCount,
required this.updated,
required this.esrbRating,
required this.platforms,
});
int id;
String slug;
String name;
DateTime released;
bool tba;
String backgroundImage;
int rating;
int ratingTop;
AddedByStatus ratings;
int ratingsCount;
String reviewsTextCount;
int added;
AddedByStatus addedByStatus;
int metacritic;
int playtime;
int suggestionsCount;
DateTime updated;
EsrbRating esrbRating;
List<Platform> platforms;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
slug: json["slug"],
name: json["name"],
released: DateTime.parse(json["released"]),
tba: json["tba"],
backgroundImage: json["background_image"],
rating: json["rating"],
ratingTop: json["rating_top"],
ratings: AddedByStatus.fromJson(json["ratings"]),
ratingsCount: json["ratings_count"],
reviewsTextCount: json["reviews_text_count"],
added: json["added"],
addedByStatus: AddedByStatus.fromJson(json["added_by_status"]),
metacritic: json["metacritic"],
playtime: json["playtime"],
suggestionsCount: json["suggestions_count"],
updated: DateTime.parse(json["updated"]),
esrbRating: EsrbRating.fromJson(json["esrb_rating"]),
platforms: List<Platform>.from(
json["platforms"].map((x) => Platform.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
"released":
"${released.year.toString().padLeft(4, '0')}-${released.month.toString().padLeft(2, '0')}-${released.day.toString().padLeft(2, '0')}",
"tba": tba,
"background_image": backgroundImage,
"rating": rating,
"rating_top": ratingTop,
"ratings": ratings.toJson(),
"ratings_count": ratingsCount,
"reviews_text_count": reviewsTextCount,
"added": added,
"added_by_status": addedByStatus.toJson(),
"metacritic": metacritic,
"playtime": playtime,
"suggestions_count": suggestionsCount,
"updated": updated.toIso8601String(),
"esrb_rating": esrbRating.toJson(),
"platforms": List<dynamic>.from(platforms.map((x) => x.toJson())),
};
}
class AddedByStatus {
AddedByStatus();
factory AddedByStatus.fromJson(Map<String, dynamic> json) => AddedByStatus();
Map<String, dynamic> toJson() => {};
}
class EsrbRating {
EsrbRating({
required this.id,
required this.slug,
required this.name,
});
int id;
String slug;
String name;
factory EsrbRating.fromJson(Map<String, dynamic> json) => EsrbRating(
id: json["id"],
slug: json["slug"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
};
}
class Platform {
Platform({
required this.platform,
required this.releasedAt,
required this.requirements,
});
EsrbRating platform;
String releasedAt;
Requirements requirements;
factory Platform.fromJson(Map<String, dynamic> json) => Platform(
platform: EsrbRating.fromJson(json["platform"]),
releasedAt: json["released_at"],
requirements: Requirements.fromJson(json["requirements"]),
);
Map<String, dynamic> toJson() => {
"platform": platform.toJson(),
"released_at": releasedAt,
"requirements": requirements.toJson(),
};
}
class Requirements {
Requirements({
required this.minimum,
required this.recommended,
});
String minimum;
String recommended;
factory Requirements.fromJson(Map<String, dynamic> json) => Requirements(
minimum: json["minimum"],
recommended: json["recommended"],
);
Map<String, dynamic> toJson() => {
"minimum": minimum,
"recommended": recommended,
};
}
Things i tried;
tried to convert response body to string before parsing
tried to change my widget to asnyc
tried to simplify my data class (to avoid arrays)
My opinion after research,
return Welcome.fromJson(jsonDecode(response.body));
this part can't work correctly cause of json decode can't decode complex datas which is has arrays and maps.
I stuck at this point and struggling. There is no document that i can do it correctly. Please help me about this.

Related

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...

Use json in the filter

Hi guys I have an api I use that responds like this:
responds
{
"RAW": {
"BTC": {
"USD": {
"TYPE": "5",
"MARKET": "CCCAGG",
"FROMSYMBOL": "BTC",
"TOSYMBOL": "USD",
"FLAGS": "1026",
"PRICE": 41091.49,
"LASTUPDATE": 1649873443,
"MEDIAN": 41085.18,
"LASTVOLUME": 0.001056,
"LASTVOLUMETO": 43.38595008,
Now to convert and use it in darts (modeling) we have to do the mapping operation, right? Does anyone know how to do this when this response is nested! I did it, but I know it's not right
My code
class CryptoEntity {
final String basecode;
// final String targetcod;
final int price;
final int volume;
final int change;
CryptoEntity.fromjason(Map<String, dynamic> jason)
: basecode = jason['FROMSYMBOL'],
// targetcod = jason['target'],
price = jason['PRICE'],
volume = jason['VOLUMEDAY'],
change = jason['LASTVOLUME'];
}
Use freezed package and json serializable for code generation, it is good for the long term development but this requires basic knowledge in flutter.
Use Online JSON to Dart converter, this site generates null safety dart class. With this solution, all you need is to change the class names after each conversion manually, and note for the fromJson factory constructor method and toJson class method.
try this:
class CryptoEntity {
final String? basecode; // ? => means that this field can be null
// final String targetcod;
final int? price;
final int? volume;
final int? change;
//constroctor
CryptoEntity(this.basecode, this.price, .. );
factory CryptoEntity.fromjason(Map<String, dynamic> jason){
return CryptoEntity(
price = jason['PRICE'],
volume = jason['VOLUMEDAY'],
change = jason['LASTVOLUME'];
);
}
}
You can turn the json into an object
import 'dart:convert';
MyModel myModelFromMap(String str) => MyModel.fromMap(json.decode(str));
String myModelToMap(MyModel data) => json.encode(data.toMap());
class MyModel {
MyModel({
required this.raw,
});
Raw raw;
factory MyModel.fromMap(Map<String, dynamic> json) => MyModel(
raw: Raw.fromMap(json["RAW"]),
);
Map<String, dynamic> toMap() => {
"RAW": raw.toMap(),
};
}
class Raw {
Raw({
required this.btc,
});
Btc btc;
factory Raw.fromMap(Map<String, dynamic> json) => Raw(
btc: Btc.fromMap(json["BTC"]),
);
Map<String, dynamic> toMap() => {
"BTC": btc.toMap(),
};
}
class Btc {
Btc({
required this.usd,
});
Usd usd;
factory Btc.fromMap(Map<String, dynamic> json) => Btc(
usd: Usd.fromMap(json["USD"]),
);
Map<String, dynamic> toMap() => {
"USD": usd.toMap(),
};
}
class Usd {
Usd({
required this.type,
required this.market,
required this.fromsymbol,
required this.tosymbol,
required this.flags,
required this.price,
required this.lastupdate,
required this.median,
required this.lastvolume,
required this.lastvolumeto,
});
String type;
String market;
String fromsymbol;
String tosymbol;
String flags;
double price;
int lastupdate;
double median;
double lastvolume;
double lastvolumeto;
factory Usd.fromMap(Map<String, dynamic> json) => Usd(
type: json["TYPE"],
market: json["MARKET"],
fromsymbol: json["FROMSYMBOL"],
tosymbol: json["TOSYMBOL"],
flags: json["FLAGS"],
price: json["PRICE"].toDouble(),
lastupdate: json["LASTUPDATE"],
median: json["MEDIAN"].toDouble(),
lastvolume: json["LASTVOLUME"].toDouble(),
lastvolumeto: json["LASTVOLUMETO"].toDouble(),
);
Map<String, dynamic> toMap() => {
"TYPE": type,
"MARKET": market,
"FROMSYMBOL": fromsymbol,
"TOSYMBOL": tosymbol,
"FLAGS": flags,
"PRICE": price,
"LASTUPDATE": lastupdate,
"MEDIAN": median,
"LASTVOLUME": lastvolume,
"LASTVOLUMETO": lastvolumeto,
};
}
You can use it like this
MyModel myModel = myModelFromMap(jsonDecode(json));
https://app.quicktype.io/

Json converted from XML not parsing with Model

I am calling an XML format API and converting it to Json to use it within a Flutter mobile app
I am using xml2Json and it is converting fine
As seen below I call print(jsonMap); and it displays the correct Json data in GData format
I then take my Json parse model, built with Quicktype.io off of the Json model and call locations = Locations.fromJson(jsonMap); as seen below to allow to to draw the required data out. I am currently then just calling print(locations); to check whether its working and the data is returning before implementing the parsed data into the app fully.
I have tried shuffling round everything, I've adapted the Model several times and tried all kinds of methods to parse the data.
I am calling other APIs with the exact same method successfully and the code method is identical in this one. The only difference is the xml2Json convert, which is converting fine (JsonMap printing converted XML correctly), so I'm struggling the see what should be different.
Thanks for reading
The call
Future<Locations> fetchLiveLocations() async {
var client = http.Client();
var locations;
Xml2Json xml2Json = new Xml2Json();
try{
var response = await client.get('API_CALL');
if (response.statusCode == 200) {
xml2Json.parse(response.body);
var jsonString = xml2Json.toGData();
var jsonMap = json.decode(jsonString);
print(jsonMap);
locations = Locations.fromJson(jsonMap);
print(locations);
}
} catch(Exception) {
return locations;
}
return locations;
}
Model
import 'dart:convert';
Locations locationsFromJson(String str) => Locations.fromJson(json.decode(str));
String locationsToJson(Locations data) => json.encode(data.toJson());
class Locations {
Locations({
this.vehicleActivity,
});
List<VehicleActivity> vehicleActivity;
factory Locations.fromJson(Map<String, dynamic> json) => Locations(
vehicleActivity: List<VehicleActivity>.from(json["VehicleActivity"].map((x) => VehicleActivity.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"VehicleActivity": List<dynamic>.from(vehicleActivity.map((x) => x.toJson())),
};
}
class VehicleActivity {
VehicleActivity({
this.recordedAtTime,
this.itemIdentifier,
this.validUntilTime,
this.monitoredVehicleJourney,
this.extensions,
});
DateTime recordedAtTime;
String itemIdentifier;
DateTime validUntilTime;
MonitoredVehicleJourney monitoredVehicleJourney;
Extensions extensions;
factory VehicleActivity.fromJson(Map<String, dynamic> json) => VehicleActivity(
recordedAtTime: DateTime.parse(json["RecordedAtTime"]),
itemIdentifier: json["ItemIdentifier"],
validUntilTime: DateTime.parse(json["ValidUntilTime"]),
monitoredVehicleJourney: MonitoredVehicleJourney.fromJson(json["MonitoredVehicleJourney"]),
extensions: Extensions.fromJson(json["Extensions"]),
);
Map<String, dynamic> toJson() => {
"RecordedAtTime": recordedAtTime.toIso8601String(),
"ItemIdentifier": itemIdentifier,
"ValidUntilTime": validUntilTime.toIso8601String(),
"MonitoredVehicleJourney": monitoredVehicleJourney.toJson(),
"Extensions": extensions.toJson(),
};
}
class Extensions {
Extensions({
this.vehicleJourney,
});
VehicleJourney vehicleJourney;
factory Extensions.fromJson(Map<String, dynamic> json) => Extensions(
vehicleJourney: VehicleJourney.fromJson(json["VehicleJourney"]),
);
Map<String, dynamic> toJson() => {
"VehicleJourney": vehicleJourney.toJson(),
};
}
class VehicleJourney {
VehicleJourney({
this.operational,
this.vehicleUniqueId,
this.driverRef,
});
Operational operational;
int vehicleUniqueId;
int driverRef;
factory VehicleJourney.fromJson(Map<String, dynamic> json) => VehicleJourney(
operational: Operational.fromJson(json["Operational"]),
vehicleUniqueId: json["VehicleUniqueId"],
driverRef: json["DriverRef"],
);
Map<String, dynamic> toJson() => {
"Operational": operational.toJson(),
"VehicleUniqueId": vehicleUniqueId,
"DriverRef": driverRef,
};
}
class Operational {
Operational({
this.ticketMachine,
});
TicketMachine ticketMachine;
factory Operational.fromJson(Map<String, dynamic> json) => Operational(
ticketMachine: TicketMachine.fromJson(json["TicketMachine"]),
);
Map<String, dynamic> toJson() => {
"TicketMachine": ticketMachine.toJson(),
};
}
class TicketMachine {
TicketMachine({
this.ticketMachineServiceCode,
this.journeyCode,
});
dynamic ticketMachineServiceCode;
int journeyCode;
factory TicketMachine.fromJson(Map<String, dynamic> json) => TicketMachine(
ticketMachineServiceCode: json["TicketMachineServiceCode"],
journeyCode: json["JourneyCode"],
);
Map<String, dynamic> toJson() => {
"TicketMachineServiceCode": ticketMachineServiceCode,
"JourneyCode": journeyCode,
};
}
class MonitoredVehicleJourney {
MonitoredVehicleJourney({
this.lineRef,
this.directionRef,
this.publishedLineName,
this.operatorRef,
this.destinationRef,
this.vehicleLocation,
this.blockRef,
this.vehicleJourneyRef,
this.vehicleRef,
});
int lineRef;
String directionRef;
int publishedLineName;
String operatorRef;
int destinationRef;
VehicleLocation vehicleLocation;
int blockRef;
String vehicleJourneyRef;
int vehicleRef;
factory MonitoredVehicleJourney.fromJson(Map<String, dynamic> json) => MonitoredVehicleJourney(
lineRef: json["LineRef"],
directionRef: json["DirectionRef"],
publishedLineName: json["PublishedLineName"],
operatorRef: json["OperatorRef"],
destinationRef: json["DestinationRef"],
vehicleLocation: VehicleLocation.fromJson(json["VehicleLocation"]),
blockRef: json["BlockRef"],
vehicleJourneyRef: json["VehicleJourneyRef"],
vehicleRef: json["VehicleRef"],
);
Map<String, dynamic> toJson() => {
"LineRef": lineRef,
"DirectionRef": directionRef,
"PublishedLineName": publishedLineName,
"OperatorRef": operatorRef,
"DestinationRef": destinationRef,
"VehicleLocation": vehicleLocation.toJson(),
"BlockRef": blockRef,
"VehicleJourneyRef": vehicleJourneyRef,
"VehicleRef": vehicleRef,
};
}
class VehicleLocation {
VehicleLocation({
this.longitude,
this.latitude,
});
double longitude;
double latitude;
factory VehicleLocation.fromJson(Map<String, dynamic> json) => VehicleLocation(
longitude: json["Longitude"].toDouble(),
latitude: json["Latitude"].toDouble(),
);
Map<String, dynamic> toJson() => {
"Longitude": longitude,
"Latitude": latitude,
};
}
Response when I request specific data from the model
NoSuchMethodError (NoSuchMethodError: The getter 'vehicleActivity' was called on null.
Receiver: null

How To Save Nested Dart Models (And Lists) As JSON In The Local File System

Here am I again with another general question:
How can I persist my (nested) model structures from Dart/Flutter in ONE JSON-File on my File System?
My models look like this:
First, my subject model:
import './topic.dart';
class Subject {
String name;
int order;
bool isMajor;
List<Topic> topics;
Subject({this.name, this.order, this.isMajor, this.topics});
factory Subject.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Subject(
name: json['name'],
order: json['order'],
isMajor: json['isMajor'],
topics: List<Topic>.from(
json['topics'].map((topic) => Topic.fromJSON(topic))));
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'isMajor': isMajor,
'topics': topics,
};
}
}
Now, the topic model:
import './content.dart';
class Topic {
String name;
int order;
List<Content> contents;
Topic({this.name, this.order, this.contents});
factory Topic.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Topic(
name: json['name'],
order: json['order'],
contents: List<Content>.from(
json['contents'].map((content) => Content.fromJSON(content))));
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'contents': contents,
};
}
}
And lastly, the content model:
class Content {
String title;
String body;
int order;
bool isImportant;
Content({this.title, this.body, this.order, this.isImportant});
factory Content.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Content(
title: json['title'],
body: json['body'],
order: json['order'],
isImportant: json['isImportant']);
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'title': title,
'body': body,
'order': order,
'isImportant': isImportant,
};
}
}
What I am interested in is the way you compile all the data into a JSON-String... OK?
If anyone has a bit of time and an idea, please feel free to answer!
Thank you for all the efforts!
Use the jsonEncode function to convert List or Map to Json strings:
Map<String, dynamic> json = {
'code' : 241,
};
String jsonString = jsonEncode(json);
In the Subject class, List<Topic> is not a supported type in json so you need to convert it to json strings:
Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'isMajor': isMajor,
'topics': topics
.map((topic) => jsonEncode(topic.toJSON()))
.toList(), // topics is now List<String>
};
}

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.