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'],
);
}
}
Related
OrderItem Model Class:
This is my OrderItem Model Class which contains a CartItem Map as I am trying to Parse this I am getting error "type 'List' is not a subtype of type 'Map<String, dynamic>'"
import 'package:flutter/cupertino.dart';
import 'package:practice_app/models/shippingAdress.dart';
import 'package:practice_app/providers/cart_provider.dart';
class OrderItem with ChangeNotifier {
final String? id;
final String? orderNo;
final DateTime? date;
final String? paymentMethod;
final ShippingAdress? shippingAdress;
final Map<String, CartItem>? cartItem;
final int? price;
OrderItem({
this.id,
this.orderNo,
this.date,
this.paymentMethod,
this.shippingAdress,
this.cartItem,
this.price,
});
factory OrderItem.fromJson(Map<String, dynamic> json) {
print('Json:');
print(json);
//tempitems
final json1 = json['order'];
Map<String, CartItem> dd = {};
final temp = CartItem.fromJson(json['order']) as Map<String, CartItem>;
final tempadd = ShippingAdress.fromJson(json['shippingAddress']) as ShippingAdress;
//final map = Map<String, CartItem>.from(temp);
print("printing temp items");
print(temp);
print("temp address");
//print(tempadd);
return OrderItem(
id: json['ProductID'].toString(),
orderNo: json['OrderNO'] ?? '',
date: json['Date'] ?? DateTime.now(),
paymentMethod: json['paymentMethod'] ?? 0,
shippingAdress: tempadd,
cartItem: temp,
price: json["price"] ?? '');
}
CartItem Model Class:
Here is the fromJson Method Define for CartItem.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CartItem {
String? id;
String? plantId;
String? title;
num? price;
int? quantity;
String? imageAssets;
String? size;
Color? color;
CartItem({
this.id,
this.plantId,
this.title,
this.price,
this.quantity,
this.imageAssets,
this.size,
this.color,
});
factory CartItem.fromJson(Map<String, dynamic> json) {
return CartItem(
id: json['id'] as String,
plantId: json['plantId'] as String,
title: json['title'] as String,
price: json['price'] as int,
quantity: json['quantity'] as int,
imageAssets: json['imageAsset'] as String,
size: json['size'] as String,
color: json['color'] ?? Colors.green[400] as Color,
);
}
Map toJson() => {
'id': this.id,
'plantId': this.plantId,
'title': this.title,
'price': this.price,
'quantity': this.quantity,
'imageAsset': this.imageAssets,
'size': this.size,
'color': this.color,
};
}
class Cart with ChangeNotifier {
Map<String, CartItem> _item = {};
Map<String, CartItem> get items {
return {..._item};
}
List<CartItem> get cartitem {
return [..._item.values.toList()];
}
int get itemCount {
return _item.length;
}
void emptyCart() {
_item.clear();
notifyListeners();
}
CartItem findById(String id) {
return _item.values.toList().firstWhere((element) => element.id == id);
}
double get totalAmount {
double total = 0.0;
_item.forEach((key, cartItem) {
total += cartItem.price! * cartItem.quantity!;
});
return total;
}
void removeItem(String productId) {
_item.remove(productId);
notifyListeners();
}
void updateCart(String id, CartItem newCart) {
// try {
if (_item.containsKey(id)) {
_item.update(
id,
(value) => CartItem(
plantId: newCart.plantId,
id: newCart.id,
title: newCart.title,
price: newCart.price,
quantity: newCart.quantity,
imageAssets: newCart.imageAssets,
size: newCart.size,
color: newCart.color,
),
);
}
notifyListeners();
// final SharedPreferences prefs = await SharedPreferences.getInstance();
// final cartData = json.encode(
// {
// _item,
// },
// );
// prefs.setString('CartData', cartData);
// } catch (error) {
// throw error;
// }
}
Future<void> addItem(String plantId, String quantity, String title,
double price, String image, String size, Color color) async {
int quantityy = quantity == '' ? 1 : int.parse(quantity);
String sizee = size == 'Small'
? 'Small'
: size == 'Large'
? 'Large'
: size == 'Extra Large'
? 'Extra Large'
: '';
try {
if (_item.containsKey(plantId)) {
//change Quantity
_item.update(
plantId,
(existingCartItem) => CartItem(
plantId: plantId,
id: existingCartItem.id,
title: existingCartItem.title,
price: existingCartItem.price,
imageAssets: existingCartItem.imageAssets,
quantity: existingCartItem.quantity! + quantityy,
size: sizee,
color: color,
),
);
} else {
_item.putIfAbsent(
plantId,
() => CartItem(
plantId: plantId,
id: DateTime.now().toString(),
title: title,
price: price,
imageAssets: image,
quantity: quantityy,
size: sizee,
color: color,
),
);
}
print(plantId);
notifyListeners();
final SharedPreferences prefs = await SharedPreferences.getInstance();
//print(${cartitem.first.});
final cartData = jsonEncode(
{
'cartItem': _item.toString(),
},
);
prefs.setString('CartData', cartData);
print(cartData);
print('Shared done');
} catch (error) {
throw error;
}
}
Future<bool> tryAutoFillCart() async {
final perfs = await SharedPreferences.getInstance();
if (!perfs.containsKey('CartData')) {
return false;
}
final fetchCartData = perfs.getString('CartData');
final extractedCartData =
jsonDecode(fetchCartData!) as Map<String, dynamic>;
_item = extractedCartData['cartItem'] as Map<String, CartItem>;
notifyListeners();
return true;
}
}
API DATA RESPONSE:
This is my Api data response I'm trying to parse specifically the order.
{
"StatusCode": 200,
"StatusMessage": "success",
"ProductID": 20,
"orderNO": 20,
"Date": null,
"paymentMethod": "Visa",
"shippingAddress": {
"ID": "20",
"FullName": "Ali",
"ShippingAddress": "Stadium Road"
},
"order": [
{
"id": "p8",
"plantId": "3",
"title": "Ali",
"imageAsset": "assets/images/plant3.png",
"price": 80,
"size": "Small",
"color": null,
"quantity": 4
},
{
"id": "p8",
"plantId": "3",
"title": "IQBAL",
"imageAsset": "assets/images/plant2.png",
"price": 80,
"size": "Small",
"color": null,
"quantity": 4
}
],
"price": 1500,
"Message": null
}
Error
Error I am getting trying to parse
I'm having problem parsin this json because I can parse "indice" but I can parse "capitulos". I get the error:
Exception has occurred. _TypeError (type 'String' is not a subtype of type 'Map')
How can I parse a list inside a list, please?
I read a great article by Pooja Bhaumik but id does not covert this example.
[
{
"id": "1",
"title": "title",
"origem": "origin",
"tipo": "type",
"indice": [
{
"id": 1,
"title": "title 1"
},
{
"id": 2,
"title": "title 2"
},
],
"capitulos": [
[
"chapter 1 text 1",
"chapter 1 text 2",
"chapter 1 text 3"
],
[
"chapter 2 text 1",
"chapter 2 text 2",
"chapter 2 text 3"
],
]
}
]
My model:
class DocumentosList {
final List<Documento> documentos;
DocumentosList({
this.documentos,
});
factory DocumentosList.fromJson(List<dynamic> parsedJson) {
List<Documento> documentos = new List<Documento>();
documentos = parsedJson.map((i) => Documento.fromJson(i)).toList();
return new DocumentosList(documentos: documentos);
}
}
class Documento {
String id;
String title;
String origem;
String tipo;
List<IndiceItem> indice;
List<Capitulos> capitulos;
Documento({
this.id,
this.title,
this.origem,
this.tipo,
this.indice,
this.capitulos,
});
factory Documento.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['indice'] as List;
List<IndiceItem> indice = list.map((i) => IndiceItem.fromJson(i)).toList();
var listCapitulos = parsedJson['capitulos'];
List<Capitulos> capitulos =
listCapitulos.map((i) => Capitulos.fromJson(i)).toList();
return new Documento(
id: parsedJson['id'],
title: parsedJson['title'],
origem: parsedJson['origem'],
indice: indice,
capitulos: capitulos,
);
}
}
class IndiceItem {
String id;
String title;
IndiceItem({
this.id,
this.title,
});
factory IndiceItem.fromJson(Map<String, dynamic> parsedJson) {
return IndiceItem(
id: parsedJson['id'].toString(),
title: parsedJson['title'],
);
}
}
class Capitulos {
final List<Capitulo> capitulos;
Capitulos({this.capitulos});
factory Capitulos.fromJson(List<dynamic> parsedJson) {
List<Capitulo> capitulos = new List<Capitulo>();
capitulos = parsedJson.map((i) => Capitulo.fromJson(i)).toList();
return new Capitulos(capitulos: capitulos);
}
}
class Capitulo {
final List<String> paragrafos;
Capitulo({this.paragrafos});
factory Capitulo.fromJson(Map<String, dynamic> parsedJson) {
var paragrafosFromJson = parsedJson['paragrafos'];
List<String> paragrafosList = paragrafosFromJson.cast<String>();
return new Capitulo(
paragrafos: paragrafosList,
);
}
}
Nothing special here, since the inner list has String type, you should use
List<List<String>> capitulos
and you should make necessary changes for fromJson and toJson as well.
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;
}
}
I am trying to convert a list of objects into a class structure from JSON. I've run into some type-errors that I can't seem to get around.
I've set up some methods to convert each piece of the objects into and from JSON and individually they work great and I've had no issues. The problem is when I try doing it with a list of all the pieces together.
Where my code gets the error:
var temp = json.decode(response.body);
var shifts = ShiftList.fromJson(temp); // This is where it breaks
ShiftList Class:
class ShiftList {
List<Shift> shifts;
ShiftList({
this.shifts,
});
addShift(Shift shift){
if(shifts == null){
shifts = [shift];
}else{
shifts.add(shift);
}
}
factory ShiftList.fromJson(Map<String, dynamic> json) {
return ShiftList(
shifts: _toObjectList(json['Shifts'], (e) => Shift.fromJson(e)),
);
}
Map<String, dynamic> toJson() {
return {
'Shifts': _fromList(shifts, (e) => e.toJson()),
};
}
}
List _fromList(data, Function(dynamic) toJson) {
if (data == null) {
return null;
}
var result = [];
for (var element in data) {
var value;
if (element != null) {
value = toJson(element);
}
result.add(value);
}
return result;
}
List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
if (data == null) {
return null;
}
var result = <T>[];
for (var element in data) {
T value;
if (element != null) {
value = fromJson(element as Map<String, dynamic>);
}
result.add(value);
}
return result;
}
Shift Class:
class Shift {
String Name;
String AccountID;
String Identifier;
UserList UserVal;
ReportList Reports;
TaskList Tasks;
String Scheduling;
String ShiftManagerCode;
Shift({
this.AccountID,
this.Name,
this.ShiftManagerCode,
this.Identifier,
this.UserVal,
this.Reports,
this.Tasks,
this.Scheduling,
});
factory Shift.fromJson(Map<String, dynamic> json) {
return Shift(
AccountID: json['AccountID'] as String,
Identifier: json['Identifier'] as String,
Name: json['ShiftName'] as String,
ShiftManagerCode: json['ShiftManagerCode'] as String,
UserVal: json['UserVal'] as UserList,
Reports: json['Reports'] as ReportList,
Tasks: json['Tasks'] as TaskList,
Scheduling: json['Scheduling'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'ShiftName': this.Name,
'AccountID': this.AccountID,
'Identifier': this.Identifier,
'ShiftManagerCode': this.ShiftManagerCode,
'UserVal': this.UserVal,
'Reports': this.Reports,
'Tasks': this.Tasks,
'Scheduling': this.Scheduling,
};
}
}
and finally, the UserList class where it gets the error:
class UserList {
List<UserObject> users;
UserList({
this.users,
});
addUser(UserObject user){
if(users == null){
users = [user];
}else{
users.add(user);
}
}
factory UserList.fromJson(Map<String, dynamic> json) {
return UserList(
users: _toObjectList(json['UserVal'], (e) => UserObject.fromJson(e)),
);
}
Map<String, dynamic> toJson() {
return {
'UserVal': _fromList(users, (e) => e.toJson()),
};
}
}
List _fromList(data, Function(dynamic) toJson) {
if (data == null) {
return null;
}
var result = [];
for (var element in data) {
var value;
if (element != null) {
value = toJson(element);
}
result.add(value);
}
return result;
}
List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
if (data == null) {
return null;
}
var result = <T>[];
for (var element in data) {
T value;
if (element != null) {
value = fromJson(element as Map<String, dynamic>);
}
result.add(value);
}
return result;
}
I expect it place the JSON object into the class structure I have in place. The specific error I get is the following:
flutter: type 'List<dynamic>' is not a subtype of type 'UserList' in typecast
the variable temp from my first code snippet is the following:
{
"Shifts": [
{
"UserVal": [
{
"UID": "test",
"Email": "test#gmail.com",
"Phone": "0000000000",
"Name": "James"
},
{
"UID": "test",
"Email": "test#gmail.com",
"Phone": "0000000000",
"Name": "Jacob"
}
],
"AccountID": "1295",
"Identifier": "JhfSC",
"ShiftManagerCode": "15A4",
"Reports": [
{
"Quantity": "3",
"User": "Jacob",
"Supplies": "ItemA",
"Subject": "Supplies",
"Note": "test"
}
],
"Scheduling": "EMPTY",
"ShiftName": "AF 37",
"Tasks": [
{
"Status": "done",
"User": "James",
"Description": "Description here",
"Name": "TaskName here"
}
]
}
]
}
Instead of creating new objects that contain your list, just have you shift class contain a property of List.
class Shift {
String Name;
String AccountID;
String Identifier;
List<UserObject> UserVal;
ReportList Reports; // do same for this
TaskList Tasks; // do same for this
String Scheduling;
String ShiftManagerCode;
Shift({
this.AccountID,
this.Name,
this.ShiftManagerCode,
this.Identifier,
this.UserVal,
this.Reports,
this.Tasks,
this.Scheduling,
});
factory Shift.fromJson(Map<String, dynamic> json) {
return Shift(
AccountID: json['AccountID'] as String,
Identifier: json['Identifier'] as String,
Name: json['ShiftName'] as String,
ShiftManagerCode: json['ShiftManagerCode'] as String,
UserVal: json['UserVal'] == null ? List<UserObject> : (json['UserVal'] as List<Dynamic>).map((dynamic map) => UserObject.fromJson(map)).toList(),
Reports: json['Reports'] as ReportList,
Tasks: json['Tasks'] as TaskList,
Scheduling: json['Scheduling'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'ShiftName': this.Name,
'AccountID': this.AccountID,
'Identifier': this.Identifier,
'ShiftManagerCode': this.ShiftManagerCode,
'UserVal': this.UserVal,
'Reports': this.Reports,
'Tasks': this.Tasks,
'Scheduling': this.Scheduling,
};
}
}
So now you can convert directly inside your from Json. You will have to do extra work in toJson to have it map correctly.
Without diving too deep into your implementation, json.decode(response.body) is returning a List<dynamic> type. You are anticipating a List<Map<String, dynamic> so you need to call .cast<Map<String, dynamic>>() on the list.
Whenever I'm trying to fetch data it's throwing exception:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
Receiver: null
Tried calling: map<Location>(Closure: (dynamic) => Location))
print(responses) is printing null on console.
This is my function to get response from api:
String url1 = 'http://192.168.43.171:3000/location';
Future<void> showLocation() async {
var response = await http.get(Uri.encodeFull(url1));
if (response.statusCode == 200) {
print(response.body);
// Map<String, dynamic> parsedMap=jsonDecode(response.body);
final data = json.decode(response.body);
final responses = Details.fromJson(data[0]);
print(responses);
// print(parsedMap['location']);
} else {
throw Exception('failed to load');
}
}
This my locationModel.dart:
class Location {
final String latitude;
final String longitude;
Location({this.latitude, this.longitude});
factory Location.fromJson(Map<String, dynamic> parsedJson) {
return Location(
latitude: parsedJson['latitude'], longitude: parsedJson['longitude']);
}
}
class Details {
final String username;
final List<Location> locations;
Details({this.username, this.locations});
factory Details.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['locations'] as List;
print(list.runtimeType);
List<Location> locationList =
list.map((i) => Location.fromJson(i)).toList();
return Details(username: parsedJson['username'], locations: locationList);
}
}
My JSON:
[
{
"id":"ABC",
"username":"xyz",
"location":[
{
"latitude": "34",
"longitude": "343"
},
{
"latitude": "34",
"longitude": "32"
}
]
}
{
"id":"ABC1",
"username":"xyz1",
"location":[
{
"latitude": "34222",
"longitude": "32243"
},
]
}
]
You have a typo:
var list = parsedJson['locations'] as List;
vs
location:[
locations != location