List<Object> conversion from netcore server api in Flutter Dart - flutter

I am trying to convert a list of objects(List<Object> in Flutter) to a defined type(class) in a flutter project. I have tried examples on converting the list as shown in Serializing Your Object in Flutter . Every time I get Map<String, dynamic> is not a subtype of List<dynamic>. But tried something different, same error. Posted is the sample code for the latter not from Serializing Your Object in Flutter. Is there an alternative to achieving this? Really appreciate your responses. [Updated]
Custom Object
#JsonSerializable(explicitToJson: true)
class Activity{
String id;
String name;
double amount;
Activity({ this.amount, this.name , this.id});
Activity.fromJson(Map<String, dynamic> json){
id = json["id"];
name = json["name"];
amount = json["amount"];
}
Map<String, dynamic> toJson() => {
'id' : id,
'name' : name,
'amount' : amount,
};
}
Sample Flutter Screen
initiateConnection(){
var builder = HubConnectionBuilder();
this._hubConnection = builder.withUrl("##########################").build();
_hubConnection.onclose( (error) => print("Connection Closed"));
this._hubConnection.on("Activities", formActivityDashboard );
this._hubConnection.start().then((data) => print("Connected"));
}
formActivityDashboard(List<Object> data){
final items = (data).map((i) => new Activity.fromJson(i));
for (final item in items) {
print(item.id);
}
}

List<dynamic>ActivityList=json.decode(response.body);
List<Activity> myActivityList = new List();
for(int i=0;i<ActivityList.length;i++)
{
Map<String, dynamic>ActivityData = ActivityList.elementAt(i);
Activity act=new Activity();
act.id=ActivityData['id']
act.name=ActivityData['name']
act.amount=ActivityData['amount']
myActivityList.add(act);
}

Related

Flutter error when converting a list to a json object removing some keys

I have an error when trying to convert a list of my object to json
My error:
Unhandled Exception: type 'RxList<ItemStockEntryModel>' is not a subtype of type 'Map<dynamic, dynamic>'
My model code:
class StockEntryModel {
final int? id;
final double costFreight;
final List<ItemStockEntryModel> items;
StockEntryModel({
this.id,
required this.costFreight,
required this.items,
});
factory StockEntryModel.fromJson(Map<String, dynamic> json) =>
StockEntryModel(
id: json['id'],
costFreight: json['costFreight'],
items: json['itemStockEntries'],
);
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items,
};
Map<String, dynamic> itemsToMap() => {
'data': items,
};
String itemsToJson() {
var data = {};
final test = itemsToMap()['data'];
final mappedItems = Map<String, dynamic>.from(test) // the error occurs here on test variable
..removeWhere((key, value) => value == null || key == 'product');
print(json.encode(mappedItems));
data['itemStockEntries'] = mappedItems;
return json.encode(data);
}
}
my goal is to return a json object like this
// is not complete, only example...
{
"itemStockEntries": {
"data": [{
"id": 2
}, {
"id": 3
}]
}
}
but i need remove keys if this value is null and my key product..
I saw some similar errors, but I couldn't find the one that actually causes it
sorry for my bad english =(
My solution based on Loren codes. I expect to help someone also
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items.map((e) => e.toJson()).toList(),
};
Map<String, dynamic> itemsToMap() => {
'data': items
.map(
(e) => e.toJson()
..removeWhere(
(key, value) => key == 'product' || value == null),
)
.toList(),
};
Map<String, dynamic> modelToJson() {
Map<String, dynamic> data = {};
data['itemStockEntries'] = itemsToMap();
data['costFreight'] = costFreight;
print(json.encode(data));
return data;
}
The .from method on a map needs a map to be passed into it, and you're passing in a list. So removeWhere is looking for keys and values which don't exist the way you're doing it.
So you could clear that first error getting rid of the itemsToMap function and changing the first 2 lines of your itemsToJson function to this.
var data = {'data': items}; // an actual map that you can pass in
final mappedItems = Map<String, dynamic>.from(data) // no more error here
But that's still a map with just a single key with a value of a list. So the removeWhere is not going to do anything of value here.
The List<ItemStockEntryModel> is what you need to be iterating through.
Assuming you have json serialization setup in your ItemStockEntryModel, this is closer to what you need to do. Not a complete example because I don't know what that model looks like, but it should give you the idea.
String itemsToJson() {
Map data = {};
List<String> jsonList = []; // new list of json strings to pass into data map
for (final item in items) {
if (// item meets whatever conditions you need) {
final jsonItem = json.encode(item);
jsonList.add(jsonItem);
}
}
data['itemStockEntries'] = {'data': jsonList};
return json.encode(data);
}

how get List<myClass> from element another List, i get CastList

My error:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Food' in type cast
I get the list from the server, using fromJson I get it in the format I need
this class contains another list of another class and I can't interact with it. when I try to pull something from the built-in list, I get an error, and the list is displayed as CastList
my class:
class FoodGroup{
#PrimaryKey()
int id;
String name;
List<Food> foods;
FoodGroup({this.name,
this.id,
this.foods});
FoodGroup.map(dynamic obj) {
this.id = obj["id"];
this.foods = obj["foods"].cast<Food>();
this.name = obj["name"];
}
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["foods"] = foods;
map["name"] = name;
return map;
}
FoodGroup.fromJson(Map<String, dynamic> json)
: id = json['id'],
foods = json['foods'].cast<Food>(),
name = json['name'];
}
. cast() I need to decode from json:
var l = jsonDecode(r.body) as List;
foodTable = l.map((i) => FoodGroup.fromJson(i)).toList();
with FoodGroup everything is ok, the problem is in List
I used json annotation and autogeneration code, this solved the problems with deserializing the nested list, but the number of files in the project has increased significantly, not very nice

Flutter: How to load JSON into a PageView

I'm hoping someone can tell me how to load JSON in to a PageView. Each page in the PageView will contain a ListView which will use Card widgets to display each Job from the JSON.
The JOB_DATE will dictate which page the job is displayed on. So in the JSON below, the first 3 items are on one date and the next 2 items are on the following date. So page 1 should display the first 3 items and page 2 should display items 4 & 5.
JSON :
{
"rows":[
{ "JOBID":23, "JOB_DATE":1588809600000, "START_TIME":"07:30", "JOB_NAME":"Cleaner" },
{ "JOBID":24, "JOB_DATE":1588809600000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":25, "JOB_DATE":1588809600000, "START_TIME":"12:30", "JOB_NAME":"Caretaker" }
{ "JOBID":26, "JOB_DATE":1588896000000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":27, "JOB_DATE":1588896000000, "START_TIME":"13:30", "JOB_NAME":"Caretaker" }
]
}
How would I code this to split the JSON up to the different pages?
Thanks heaps for any help.
Cheers,
Paul
You can you groupBy function from 'package:collection/collection.dart'
var json = {
"rows":[
{ "JOBID":23, "JOB_DATE":1588809600000, "START_TIME":"07:30", "JOB_NAME":"Cleaner" },
{ "JOBID":24, "JOB_DATE":1588809600000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":25, "JOB_DATE":1588809600000, "START_TIME":"12:30", "JOB_NAME":"Caretaker" }
{ "JOBID":26, "JOB_DATE":1588896000000, "START_TIME":"08:30", "JOB_NAME":"Manager" }
{ "JOBID":27, "JOB_DATE":1588896000000, "START_TIME":"13:30", "JOB_NAME":"Caretaker" }
]
}
List<Map<String, dynamic> rows = json['rows']
Map<dynamic, List<Map<String, dynamic>> sortedRow = groupBy(rows, (row) => row['JOB_DATE']
And you will have a map where keys are (1588809600000, 1588896000000) and values are lists of your objects.
After that you can create PageView with a ListView of your objects
I would use something like this Json to dart class converter to quickly get a dart class for you JSON data structure. Then I would use the resulting dart class to parse your Json into a list of jobs in dart and then use that list on a specific page's ListView data source by only selecting the values with the specific sTARTTIME value you want to display on that page.
class Job {
List<Rows> rows;
Job({this.rows});
Job.fromJson(Map<String, dynamic> json) {
if (json['rows'] != null) {
rows = new List<Rows>();
json['rows'].forEach((v) {
rows.add(new Rows.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.rows != null) {
data['rows'] = this.rows.map((v) => v.toJson()).toList();
}
return data;
}
}
class Rows {
int jOBID;
int jOBDATE;
String sTARTTIME;
String jOBNAME;
Rows({this.jOBID, this.jOBDATE, this.sTARTTIME, this.jOBNAME});
Rows.fromJson(Map<String, dynamic> json) {
jOBID = json['JOBID'];
jOBDATE = json['JOB_DATE'];
sTARTTIME = json['START_TIME'];
jOBNAME = json['JOB_NAME'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['JOBID'] = this.jOBID;
data['JOB_DATE'] = this.jOBDATE;
data['START_TIME'] = this.sTARTTIME;
data['JOB_NAME'] = this.jOBNAME;
return data;
}
}
You can parse our JSON like this in your flutter app:
import 'dart:convert';
...
Job jobs = Job.fromJson(json.decode(jsonString));
...
final firstPageData = jobs.rows.where((row) => row.jOBDATE == 1588809600000).toList();
final secondPageData = jobs.rows.where((row) => row.jOBDATE == 1588896000000).toList();

Map of object containing a List<Object> for sqlite

I am setting up my model classes to confirm to the docs for sqflite which suggest including a named constructor to convert to/from Maps to better handling of data between the classes and the DB. Every example I can find is very simple, with class properties all being simple data types.
Using the constructor and method shown below, converting to/from Map is quite simple when dealing with a class such as this.
class Human{
final String name;
final String height;
Final String weight;
Human({this.name, this.height, this.weight});
}
However, when you have a class where one of the fields is a bit more complex, I do not understand how to structure things within the named constructor and xxx method to return the map of data that I 'believe' I should get.
class Human{
final String name;
final String height;
Final String weight;
List<Child> children = [];
Human({this.name, this.height, this.weight, this.children});
}
Human({this.name, this.height, this.weight, this.children});
Human.fromMap(Map<String, dynamic> map)
: name = map['name'],
height = map['height'],
weight = map['weight'],
children = map['children'];
Map<String, dynamic> toMap() {
return {
'name': name,
'height': height,
'weight': weight,
'children': children,
};
}
The List children is the part I am struggling with. I believe you have to get each Child object ALSO converted to a map within the parent map, but am losing the battle here.
Is my approach way off here? Is there some other method I should be using to accomplish this?
Any assistance would be much appreciated.
Here I am explaining the following
How to convert a model object into Map to use with sqlite
How to convert a Map object from sqlite into a model class.
How to parse JSON reponse properly in flutter
How to convert a model object into JSON
All of the above questions has same answer. Dart has great support for these operations. Here I am going to illustrate it with a detailed example.
class DoctorList{
final List<Doctor> doctorList;
DoctorList({this.doctorList});
factory DoctorList.fromMap(Map<String, dynamic> json) {
return DoctorList(
doctorList: json['doctorList'] != null
? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
: null,
);
}
Map<String, dynamic> toMap() {
final Map<String, dynamic> data = Map<String, dynamic>();
if (this.doctorList != null) {
data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
}
return data;
}
}
The above DoctorList class has a member which holds a list of 'Doctor' objects..
And see how I parsed the doctorList.
doctorList: json['doctorList'] != null
? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
: null,
You may wonder, how the Doctor class may look like. Here you go
class Doctor {
final String doCode;
final String doctorName;
Doctor({this.doCode, this.doctorName});
factory Doctor.fromMap(Map<String, dynamic> json) {
return Doctor(
doCode: json['doCode'],
doctorName: json['doctorName'],
);
}
Map<String, dynamic> toMap() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['doCode'] = this.doCode;
data['doctorName'] = this.doctorName;
return data;
}
}
That's all. Hope you got the idea. Cheers!

How to convert an array to a dart object

I have the following structure that is returned from my API. How do I convert it to a dart object?
[
{
"stateName": "Alabama",
"stateAbbr": "AL"
},
{
"stateName": "Alaska",
"stateAbbr": "AK"
}
]
Basically, I want to display a flutter dropdown box with the stateName value..
It's a list of maps.
first make a State class:
class State{
final String stateName;
final String stateAbbr;
State({
this.stateName,
this.stateAbbr,
}) ;
factory State.fromJson(Map<String, dynamic> json){
return new State(
id: json['stateName'],
title: json['stateAbbr'],
);
}
}
then list of States:
class StatesList {
final List<State> States;
StatesList({
this.States,
});
factory StatesList.fromJson(List<dynamic> parsedJson) {
List<State> States = new List<State>();
States = parsedJson.map((i)=>State.fromJson(i)).toList();
return new StatesList(
States: States,
);
}
}
for more information read this article
class State {
String stateName;
String stateAbbr;
State({this.stateName, this.stateAbbr});
State.fromJson(Map<String, dynamic> json) {
stateName = json['stateName'];
stateAbbr = json['stateAbbr'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['stateName'] = this.stateName;
data['stateAbbr'] = this.stateAbbr;
return data;
}
}
use this website [https://javiercbk.github.io/json_to_dart/][1] it can help you to convert any object JSON to Dart class, and after that, you should use List Object of type State.