How to get the object from array from api response in flutter - json

I'm trying to integrate the api using class model. here is my api response look like.
{
"status": 1,
"message": "your rides",
"data": [
{
"id": 2,
"ride_user_id": "4",
"ride_driver_id": "2",
"pick_up": "gsdhjhsgdf",
"drop_of": "dsfbsdjbf",
"date": null,
"time": "10.55",
"status": "complete",
"created_at": "2022-06-17T09:50:25.000000Z",
"updated_at": "2022-06-17T09:56:37.000000Z",
"driver": {
"id": 2,
"name": "driver",
"vehicle_number": null,
"licence_number": null,
"state": null,
"image": null,
"notification": 1,
"created_at": "2022-06-08T16:15:12.000000Z",
"updated_at": "2022-06-08T16:15:44.000000Z"
},
"rideperson": {
"id": 4,
"name": "ab",
"vehicle_number": null,
"licence_number": null,
"state": "ascascas",
"image": "profile/1735772987889499.jfif",
"notification": 1,
"created_at": "2022-06-09T07:54:41.000000Z",
"updated_at": "2022-06-16T06:48:37.000000Z"
},
"rating": {
"id": 2,
"sender_id": null,
"reciever_id": null,
"ride_id": 2,
"rating": "4",
"created_at": "2022-06-17T09:59:38.000000Z",
"updated_at": "2022-06-17T09:59:38.000000Z"
}
}
]
}
and here is my model
import 'dart:convert';
import 'package:flutter/foundation.dart';
MyRides rideFromJson(String str) => MyRides.fromJson(json.decode(str));
String rideToJson(MyRides data) => json.encode(data.toJson());
class MyRidesDetails {
final int id;
final String pickUp;
final String dropOff;
final String time;
final String rideUserId;
final String rideDriverId;
final List driver;
MyRidesDetails(
{required this.id,
required this.pickUp,
required this.dropOff,
required this.time,
required this.rideUserId,
required this.rideDriverId,
required this.driver
});
factory MyRidesDetails.fromJson(Map<String, dynamic> json) => MyRidesDetails(
id: json['id'],
dropOff: json['drop_of'],
pickUp: json['pick_up'],
time: json['time'],
rideUserId: json['ride_user_id'],
rideDriverId: json['ride_driver_id'],
driver: json['data']['driver']
);
Map<String, dynamic> toJson() => {
'id': id,
'drop_of': dropOff,
'pick_up': pickUp,
'time':time,
'rating':time,
'ride_user_id':rideUserId,
'ride_driver_id':rideDriverId,
'driver':driver
};
}
class MyRides {
MyRides({
required this.status,
required this.message,
required this.data,
});
int status;
String message;
List<MyRidesDetails> data;
factory MyRides.fromJson(Map<String, dynamic> json) => MyRides(
status: json["status"],
message: json["message"],
data: List<MyRidesDetails>.from(json["data"].map((x) => MyRidesDetails.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
here is the code how i'm populating data on my model
Future getAllMyRides(role) async {
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllMyRidesUrl+role);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
return rideFromJson(response.body).data;
} else {
throw Exception('Failed to load post');
}
}
Now, the question is i want to access this object
"driver": {
"id": 2,
"name": "driver",
"vehicle_number": null,
"licence_number": null,
"state": null,
"image": null,
"notification": 1,
"created_at": "2022-06-08T16:15:12.000000Z",
"updated_at": "2022-06-08T16:15:44.000000Z"
},
using the same model. My model is only accessing the data which is not in object, i want to create a list variable or something on my mode which can access those data which is in object form.
here is the code how i'm calling api function on ui screen
getAllMyRides() async {
setState(() {
_isLoading = true;
});
await Future.delayed(const Duration(seconds: 2), () async {
connectionMsg = await services.checkInternetConnectivity();
if (connectionMsg == "connected") {
try {
var _myRides = await services.getAllMyRides(role);
if (myRides is MyRides) {
print(_myRides.data[0].driver.id); //this should print 2
} else {
print("Unable to fetch data");
}
setState(() {
_isLoading = false;
});
} catch (e) {
print(e);
setState(() {
apiCrashed = true;
});
}
setState(() {
_isLoading = false;
});
} else if (connectionMsg == "not connected") {
AppDialogs().showInfoDialogue(context, "Internet is not working!", () {
Navigator.pop(context);
});
setState(() {
_isLoading = false;
});
}
});
}
#override
void initState() {
super.initState();
getAllMyRides();
}
please help how to do this.Thanks.

var _myRides = await getAllMyRides();
var jsonDecoded = json.decode(_myRides);
print(jsonDecoded['data'][0]['driver']['id']);
please try this

Related

Flutter jsonDecode returns String instead of List

I want to decode my json to a List but jsonDecode returns String instead of List.
My JSON:
[{
"TicketID": 31,
"EmpID": "11553",
"Name": "Test",
"Location": null,
"PhoneExt": 345345,
"Code": null,
"Reason": null,
"Category": null,
"Created": null,
"Username": "abc",
"OtherLocation": null,
"Room": null,
"Floor": null,
"CodeBlueDone": null,
"CodeBlueDoneDate": null,
"LocationCode": null,
"PatientType": null,
"EmergencyType": "Emergency",
"FilledDateTime": null,
"SubmitDateTime": null,
"Type": null,
"CallTime": "2022-08-26T13:43:25.003",
"Status": "New"
}, {
"TicketID": 30,
"EmpID": "12",
"Name": "dbdb",
"Location": null,
"PhoneExt": 123,
"Code": null,
"Reason": null,
"Category": null,
"Created": null,
"Username": "abc",
"OtherLocation": null,
"Room": null,
"Floor": null,
"CodeBlueDone": null,
"CodeBlueDoneDate": null,
"LocationCode": null,
"PatientType": null,
"EmergencyType": "Emergency",
"FilledDateTime": null,
"SubmitDateTime": null,
"Type": null,
"CallTime": "2022-08-25T21:14:39.807",
"Status": "New"
}]
if (response.statusCode == 200) {
jsonDecode(response.body);
print(jsonDecode(response.body).runtimeType);
}
Future<List> _getDataFromWeb() async {
try {
await http.post(
Uri.parse(apiURL),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
).then((response) {
if (response.statusCode == 200) {
try {
final resp = jsonDecode(response.body) as List?;
print(resp.runtimeType);
} catch (ex) {
print("_getDataFromWeb() error: ${ex}");
}
} else if (response.statusCode == 404) {
print("Error 404: ${response.statusCode}");
} else {
print("Error: ${response.statusCode}");
}
}).catchError((error) {
print("Error: " + error);
});
} catch (ex) {
print("API-ERR: $ex");
}
}
Full code to decode is given above
Why the flutter jsonDecode or json.Decode doesn't return a List from above JSON?
EDIT
Calling jsonDecode two times works and returns List
final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);
I wonder why calling jsonDecode() two times is needed?
Calling jsonDecode two times works and returns List
final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);
Finally found the answer after investing hours into it.
Try like this
final response = jsonDecode(response.body) as List?;
print(response.runtimeType);
Try this code via QuickType
// To parse this JSON data, do
//
// final model = modelFromJson(jsonString);
import 'dart:convert';
List<Model> modelFromJson(String str) => List<Model>.from(json.decode(str).map((x) => Model.fromJson(x)));
String modelToJson(List<Model> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Model {
Model({
this.ticketId,
this.empId,
this.name,
this.location,
this.phoneExt,
this.code,
this.reason,
this.category,
this.created,
this.username,
this.otherLocation,
this.room,
this.floor,
this.codeBlueDone,
this.codeBlueDoneDate,
this.locationCode,
this.patientType,
this.emergencyType,
this.filledDateTime,
this.submitDateTime,
this.type,
this.callTime,
this.status,
});
int ticketId;
String empId;
String name;
dynamic location;
int phoneExt;
dynamic code;
dynamic reason;
dynamic category;
dynamic created;
String username;
dynamic otherLocation;
dynamic room;
dynamic floor;
dynamic codeBlueDone;
dynamic codeBlueDoneDate;
dynamic locationCode;
dynamic patientType;
String emergencyType;
dynamic filledDateTime;
dynamic submitDateTime;
dynamic type;
DateTime callTime;
String status;
factory Model.fromJson(Map<String, dynamic> json) => Model(
ticketId: json["TicketID"],
empId: json["EmpID"],
name: json["Name"],
location: json["Location"],
phoneExt: json["PhoneExt"],
code: json["Code"],
reason: json["Reason"],
category: json["Category"],
created: json["Created"],
username: json["Username"],
otherLocation: json["OtherLocation"],
room: json["Room"],
floor: json["Floor"],
codeBlueDone: json["CodeBlueDone"],
codeBlueDoneDate: json["CodeBlueDoneDate"],
locationCode: json["LocationCode"],
patientType: json["PatientType"],
emergencyType: json["EmergencyType"],
filledDateTime: json["FilledDateTime"],
submitDateTime: json["SubmitDateTime"],
type: json["Type"],
callTime: DateTime.parse(json["CallTime"]),
status: json["Status"],
);
Map<String, dynamic> toJson() => {
"TicketID": ticketId,
"EmpID": empId,
"Name": name,
"Location": location,
"PhoneExt": phoneExt,
"Code": code,
"Reason": reason,
"Category": category,
"Created": created,
"Username": username,
"OtherLocation": otherLocation,
"Room": room,
"Floor": floor,
"CodeBlueDone": codeBlueDone,
"CodeBlueDoneDate": codeBlueDoneDate,
"LocationCode": locationCode,
"PatientType": patientType,
"EmergencyType": emergencyType,
"FilledDateTime": filledDateTime,
"SubmitDateTime": submitDateTime,
"Type": type,
"CallTime": callTime.toIso8601String(),
"Status": status,
};
}
Make sure response.body is in correct type and format. And try decoding via this code:
final List<dynamic> decodedResponseBody = jsonDecode(response.body);
resource: https://api.flutter.dev/flutter/dart-convert/jsonDecode.html
Try
json.decode(response.body) as List;
EDIT
Try this format
Future<List> _getDataFromWeb() async {
try {
var response = await http.post(
Uri.parse(apiURL),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
);
if (response.statusCode == 200) {
try {
final resp = json.decode(response.body.toString()) as List?;
print(resp.runtimeType);
} catch (ex) {
print("_getDataFromWeb() error: ${ex}");
}
} else if (response.statusCode == 404) {
print("Error 404: ${response.statusCode}");
} else {
print("Error: ${response.statusCode}");
}
}
} catch (ex) {
print("API-ERR: $ex");
}
}

How to get json array in Flutter/Dart

I would want to get the data for all "name" only from the array data.
I want to print(data['data']['name']);
But it returns this error:
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
But when I print(data['data']);, it will return all data from "data":
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
......
],
Call API Code
displayBanks(BuildContext context) async {
_callApi.refreshTokenApi(context);
var _addressUrl = '$_hostUrl/banks'; //API URL
final SharedPreferences prefs = await SharedPreferences.getInstance();
_accessToken = prefs.getString('access_token');
Response _response = await get(_addressUrl, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_accessToken'
});
var data;
data = jsonDecode(_response.body);
if (_response.statusCode == 200) {
print(data['data']['name']);
return data;
}
else {
print(_response.statusCode);
}
}
SAMPLE JSON DATA FROM API URL:
{
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 3,
"is_active": 1,
"name": "India International Bank (Malaysia) Berhad",
"updated_at": "2020-03-16 16:27:37"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 4,
"is_active": 1,
"name": "National Bank of Abu Dhabi Malaysia Berhad",
"updated_at": "2020-03-16 16:27:37"
}
],
"links": {
"first": "https://demo.local/api/banks?page=1",
"last": "https://demo.local/api/banks?page=1",
"next": null,
"prev": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "https://demo.local/api/banks",
"per_page": 5,
"to": 3,
"total": 3
}
}
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
The exception message explains the issue clearly.
The property 'name' is inside an object which itself placed in an array. So you first decode the array. Then access each object using the index (0..n), then from each object, you can read the 'name' property.
Here you go
class MyData {
final List<Data> data;
MyData({this.data});
factory MyData.fromJson(Map<String, dynamic> json) {
return MyData(
data: json['data'] != null ? (json['data'] as List).map((i) => Data.fromJson(i)).toList() : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
final String created_at;
final String deleted_at;
final int id;
final int is_active;
final String name;
final String updated_at;
Data({this.created_at, this.deleted_at, this.id, this.is_active, this.name, this.updated_at});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
created_at: json['created_at'],
deleted_at: json['deleted_at'],
id: json['id'],
is_active: json['is_active'],
name: json['name'],
updated_at: json['updated_at'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created_at'] = this.created_at;
data['id'] = this.id;
data['is_active'] = this.is_active;
data['name'] = this.name;
data['updated_at'] = this.updated_at;
data['deleted_at'] = this.deleted_at;
return data;
}
}
The error makes sense. The 'data' attribute in your JSON is array. So, you'll have to pass index of the item to access 'name' attribute - something like - data['data'][0]['name'] to get 'Maybank'.
Ideally, you should have a class which creates the instance from the JSON. In this case, the code snippet will look like :
Banks banks = new Banks.fromJson(data)
Now, you can use sites like this to create a class definition (including.fromJson).

Unexpected error while parsing JsonData in flutter

Am trying to parse json list data so I could save into an object. But I kept getting errors each time and I do not know why.
Json Data
{
"status": "success",
"data": [
{
"distro_name": "Ikeja Electric (IKEDC)",
"service_id": "ikeja-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Eko Electric (EKEDC)",
"service_id": "eko-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Ibadan Electric (IBEDC)",
"service_id": "ibadan-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Kano Electric (KEDCO)",
"service_id": "kano-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Jos Electricity Distribution (JED)",
"service_id": "jos-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Port-Harcourt Electric (PHED)",
"service_id": "portharcourt-electric",
"type": [
"prepaid",
"postpaid"
]
}
]
}
This is my model class for the data.
Model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
Providers.fromJson(Map<String, dynamic> json):
distro_name = json['distro_name'],
service_id = json['service_id'],
type = json['type'];
}
Main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
for (var u in responseJson["data"]) {
Providers provider = Providers(
u["distro_name"],
u["service_id"],
u["list"]);
providerList.add(provider);
}
return responseJson;
} catch (exception) {
print(exception);
}
}
This is the error I get.
NoSuchMethodError: The method 'add' was called on null.
I/flutter ( 1366): Receiver: null
I don't really know why I get this error. I don't have null values on my api and I have consumed these kind of json structure in the past.
Initialize providerList:
var providerList = </* type */>[]
for (var u in responseJson["data"]) {
Providers provider = Providers(
u["distro_name"],
u["service_id"],
u["list"]);
providerList.add(provider);
}
Using list map:
providerList = responseJson["data"].map((u) => Providers(
u["distro_name"],
u["service_id"],
u["list"],
)).cast<String>().toList();
Model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
Providers.fromJson(Map<String, dynamic> json) => Providers(
json['distro_name'],
json['service_id'],
json['type'],
);
}
Main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
responseJson.forEach((data){
Providers provider = Providers.fromJson(data);
providerList.add(provider);
return responseJson;
});
} catch (exception) {
print(exception);
}
}
model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
factory Providers.fromJson(Map<String, dynamic> json){
return Providers(
distro_name = json['distro_name'],
service_id = json['service_id'],
type = json['type'],
);
}
}
main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
for (var u in responseJson['data']) {
Providers provider = Providers.fromJson(u);
providerList.add(provider);
return responseJson;
}
}
catch (exception) {
print(exception);
}
}

How can i get all the commands id from a JSON file in flutter?

i'm a beginner in flutter and i'm trying to get values from a JSON file with flutter.
I could get some the values of the device id and devices name but i really don'y know how to get the id in commands.
Thank you in advance for your help.
Here is my JSON file :
[
{
"id": "15622bf9-969c-4f54-bd80-265a8132c97a",
"name": "Random-Integer-Generator01",
"adminState": "UNLOCKED",
"operatingState": "ENABLED",
"lastConnected": 0,
"lastReported": 0,
"labels": [
"device-random-example"
],
"location": null,
"commands": [
{
"created": 1572962679310,
"modified": 1572962679310,
"id": "f07b4a42-4358-4394-bc71-76f292f8359f",
"name": "GenerateRandomValue_Int8",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
"parameterNames": [
"Min_Int8",
"Max_Int8"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
}
},
{
"created": 1572962679336,
"modified": 1572962679336,
"id": "86eafeb6-f359-40e7-b6c1-d35e9e9eb625",
"name": "GenerateRandomValue_Int16",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
"parameterNames": [
"Min_Int16",
"Max_Int16"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
}
},
{
"created": 1572962679337,
"modified": 1572962679337,
"id": "bb492384-8c72-4ab6-9a84-24a3be0b934e",
"name": "GenerateRandomValue_Int32",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
"parameterNames": [
"Min_Int32",
"Max_Int32"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
}
}
]
},
{
"id": "97dcd3b2-f4f1-4a1a-9520-2ff62c697945",
"name": "Random-Boolean-Device",
"adminState": "UNLOCKED",
"operatingState": "ENABLED",
"lastConnected": 0,
"lastReported": 0,
"labels": [
"device-virtual-example"
],
"location": null,
"commands": [
{
"created": 1572962679576,
"modified": 1572962679576,
"id": "1bc520ef-a9a4-43c7-8098-dcc5faea9ea1",
"name": "RandomValue_Bool",
"get": {
"path": "/api/v1/device/{deviceId}/RandomValue_Bool",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
},
"put": {
"path": "/api/v1/device/{deviceId}/RandomValue_Bool",
"parameterNames": [
"RandomValue_Bool",
"EnableRandomization_Bool"
],
"url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
}
}
]
},
]
Here is my main flutter code :
import 'dart:convert';
import 'package:flutter/material.dart';
import 'GET.dart';
import 'Device.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Http App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}
class MyListScreen extends StatefulWidget {
#override
createState() => _MyListScreenState();
}
class _MyListScreenState extends State {
var device = new List<Device>();
_getDevice() {
GET.getDevice().then((response) {
setState(() {
Iterable list = json.decode(response.body);
device = list.map((model) => Device.fromJson(model)).toList();
});
});
}
initState() {
super.initState();
_getDevice();
}
dispose() {
super.dispose();
}
#override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("Device List"),
),
body: ListView.builder(
itemCount: device.length,
itemBuilder: (context, index) {
return ListTile(title: Text("Num $index "+device[index].id));
},
));
}
}
And here is my Device class :
class Device {
//String
String id;
String name;
//String commands;
Device(String id, String name) {
this.id = id;
this.name = name;
//this.commands = commands;
//this.email = email;
}
Device.fromJson(Map json)
: id = json['id'],
name = json['name'];
// commands = json['commands'];
//['commands'][0]['name'], // marche
//email = json['email'];
Map toJson() {
return {'id': id, 'name': name};
}
}
you can cast json with below class and get commands of device with device[index].commands
class Device {
String id;
String name;
String adminState;
String operatingState;
int lastConnected;
int lastReported;
List<String> labels;
Null location;
List<Commands> commands;
Device(
{this.id,
this.name,
this.adminState,
this.operatingState,
this.lastConnected,
this.lastReported,
this.labels,
this.location,
this.commands});
Device.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
adminState = json['adminState'];
operatingState = json['operatingState'];
lastConnected = json['lastConnected'];
lastReported = json['lastReported'];
labels = json['labels'].cast<String>();
location = json['location'];
if (json['commands'] != null) {
commands = new List<Commands>();
json['commands'].forEach((v) {
commands.add(new Commands.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['adminState'] = this.adminState;
data['operatingState'] = this.operatingState;
data['lastConnected'] = this.lastConnected;
data['lastReported'] = this.lastReported;
data['labels'] = this.labels;
data['location'] = this.location;
if (this.commands != null) {
data['commands'] = this.commands.map((v) => v.toJson()).toList();
}
return data;
}
}
class Commands {
int created;
int modified;
String id;
String name;
Get get;
Put put;
Commands(
{this.created, this.modified, this.id, this.name, this.get, this.put});
Commands.fromJson(Map<String, dynamic> json) {
created = json['created'];
modified = json['modified'];
id = json['id'];
name = json['name'];
get = json['get'] != null ? new Get.fromJson(json['get']) : null;
put = json['put'] != null ? new Put.fromJson(json['put']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created'] = this.created;
data['modified'] = this.modified;
data['id'] = this.id;
data['name'] = this.name;
if (this.get != null) {
data['get'] = this.get.toJson();
}
if (this.put != null) {
data['put'] = this.put.toJson();
}
return data;
}
}
class Get {
String path;
List<Responses> responses;
String url;
Get({this.path, this.responses, this.url});
Get.fromJson(Map<String, dynamic> json) {
path = json['path'];
if (json['responses'] != null) {
responses = new List<Responses>();
json['responses'].forEach((v) {
responses.add(new Responses.fromJson(v));
});
}
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['path'] = this.path;
if (this.responses != null) {
data['responses'] = this.responses.map((v) => v.toJson()).toList();
}
data['url'] = this.url;
return data;
}
}
class Responses {
String code;
String description;
Responses({this.code, this.description});
Responses.fromJson(Map<String, dynamic> json) {
code = json['code'];
description = json['description'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
data['description'] = this.description;
return data;
}
}
class Put {
String path;
List<String> parameterNames;
String url;
Put({this.path, this.parameterNames, this.url});
Put.fromJson(Map<String, dynamic> json) {
path = json['path'];
parameterNames = json['parameterNames'].cast<String>();
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['path'] = this.path;
data['parameterNames'] = this.parameterNames;
data['url'] = this.url;
return data;
}
}

How to get all fields from Dio request in Flutter

I'm using Dio to get a request from this Api: Api Example
The response is like:
{
"count": 87,
"next": "https://swapi.co/api/people/?page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
},
And I have this code in dart:
void _getNames() async {
final response = await dio.get('https://swapi.co/api/people');
List tempList = new List();
for (int i = 0; i < response.data['results'].length; i++) {
tempList.add(response.data['results'][i]);
}
setState(() {
names = tempList;
names.shuffle();
filteredNames = names;
});
}
With this code, i only get the name of the results but i don't know how to get the other fields, i've tried some things but nothing works. I know that it would be very easy but i don't know how to do.
Here you go
_getPeople() async {
var response = await http.get('https://swapi.co/api/people/');
if (response != null && response.statusCode == 200) {
ResultModel jsonResponse =
ResultModel.fromJson(convert.jsonDecode(response.body));
print(jsonResponse);
}
}
ResultModel code is
class ResultModel {
int count;
String next;
dynamic previous;
List<Result> results;
ResultModel({
this.count,
this.next,
this.previous,
this.results,
});
factory ResultModel.fromJson(Map<String, dynamic> json) {
return ResultModel(
count: json['count'],
next: json['next'],
previous: json['previous'],
results: _parseResult(json['results']),
);
}
}
_parseResult(List<dynamic> data) {
List<Result> results = new List<Result>();
data.forEach((item) {
results.add(Result.fromJson(item));
});
return results;
}
_parseString(List<dynamic> data) {
List<String> results = new List<String>();
data.forEach((item) {
results.add(item);
});
return results;
}
class Result {
String name;
String height;
String mass;
String hairColor;
String skinColor;
String eyeColor;
String birthYear;
String gender;
String homeworld;
List<String> films;
List<String> species;
List<String> vehicles;
List<String> starships;
String created;
String edited;
String url;
Result({
this.name,
this.height,
this.mass,
this.hairColor,
this.skinColor,
this.eyeColor,
this.birthYear,
this.gender,
this.homeworld,
this.films,
this.species,
this.vehicles,
this.starships,
this.created,
this.edited,
this.url,
});
factory Result.fromJson(Map<String, dynamic> json) {
return Result(
name: json['name'],
height: json['height'],
mass: json['mass'],
hairColor: json['hairColor'],
skinColor: json['skinColor'],
eyeColor: json['eyeColor'],
birthYear: json['birthYear'],
gender: json['gender'],
homeworld: json['homeworld'],
films: _parseString(json['films']),
species: _parseString(json['species']),
vehicles: _parseString(json['vehicles']),
created: json['created'],
edited: json['edited'],
url: json['url'],
);
}
}