Get array from json flutter - arrays

Trying to get plant info and found https://trefle.io/ Api, to use in my flutter app, i need list of plant infos, so i found a json structure like this;
I'm trying fetch data from api array and implement it my ListView.builder, but i'm getting error;
type 'Future' is not a subtype of type 'Map<String, dynamic>'
So What's the most efficient way of fetching array data from json
List View
ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
Plant plant = Plant.fromJson(decodedData);
Data data = plant.data[index];
Container(
child: Image(
image: NetworkImage(data.imageUrl),
),
);
}),
FETCH DATA
Future<dynamic> fetchData(String url, bool asyncCall) async {
asyncCall = true;
response = await http.get(url);
decoded = json.encode(response.body);
return decoded;
}
PLANT
class Plant {
List<Data> data;
Plant({this.data});
Plant.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
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;
}
}
DATA
class Data {
int id;
String commonName;
String slug;
String scientificName;
int year;
String bibliography;
String author;
String status;
String rank;
String familyCommonName;
int genusId;
String imageUrl;
List<String> synonyms;
String genus;
String family;
Data({
this.id,
this.commonName,
this.slug,
this.scientificName,
this.year,
this.bibliography,
this.author,
this.status,
this.rank,
this.familyCommonName,
this.genusId,
this.imageUrl,
this.synonyms,
this.genus,
this.family,
});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
commonName = json['common_name'];
slug = json['slug'];
scientificName = json['scientific_name'];
year = json['year'];
bibliography = json['bibliography'];
author = json['author'];
status = json['status'];
rank = json['rank'];
familyCommonName = json['family_common_name'];
genusId = json['genus_id'];
imageUrl = json['image_url'];
synonyms = json['synonyms'].cast<String>();
genus = json['genus'];
family = json['family'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['common_name'] = this.commonName;
data['slug'] = this.slug;
data['scientific_name'] = this.scientificName;
data['year'] = this.year;
data['bibliography'] = this.bibliography;
data['author'] = this.author;
data['status'] = this.status;
data['rank'] = this.rank;
data['family_common_name'] = this.familyCommonName;
data['genus_id'] = this.genusId;
data['image_url'] = this.imageUrl;
data['synonyms'] = this.synonyms;
data['genus'] = this.genus;
data['family'] = this.family;
return data;
}
}
To Solve
Added this func below
Plant plant;
Future<void> getPlant() async {
String url =
'https://trefle.io/api/v1/plants?token=jAEYseuuPFUlUss9QcNOefanIBG_fb83mkXdaRDIu8w';
Map<String, String> header = {"Content-type": "application/json"};
// make GET request
var response = await http.get(url, headers: header);
// check the status code for the result
if (response.statusCode == 200) {
setState(() {
plant = plantFromJson(response.body);
});
} else {}
}
changed fetchData
Future<Plant> fetchData(String url, bool asyncCall) async {
asyncCall = true;
response = await http.get(url);
final plant = plantFromJson(response.body);
print(plant);
print(plant.data);
print(plant.data[0].imageUrl);
return plant;
}

import 'dart:convert';
Plant plantFromJson(String str) => Plant.fromJson(json.decode(str));
String plantToJson(Plant data) => json.encode(data.toJson());
class Plant {
Plant({
this.data,
this.links,
this.meta,
});
List<Data> data;
PlantLinks links;
Meta meta;
factory Plant.fromJson(Map<String, dynamic> json) => Plant(
data: List<Data>.from(json["data"].map((x) => Data.fromJson(x))),
links: PlantLinks.fromJson(json["links"]),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"links": links.toJson(),
"meta": meta.toJson(),
};
}
class Data {
Data({
this.author,
this.bibliography,
this.commonName,
this.family,
this.familyCommonName,
this.genus,
this.genusId,
this.id,
this.links,
this.plantId,
this.rank,
this.scientificName,
this.slug,
this.status,
this.synonyms,
this.year,
});
String author;
String bibliography;
dynamic commonName;
String family;
String familyCommonName;
String genus;
int genusId;
int id;
DatumLinks links;
int plantId;
String rank;
String scientificName;
String slug;
String status;
List<String> synonyms;
int year;
factory Data.fromJson(Map<String, dynamic> json) => Data(
author: json["author"],
bibliography: json["bibliography"],
commonName: json["common_name"],
family: json["family"],
familyCommonName: json["family_common_name"] == null ? null : json["family_common_name"],
genus: json["genus"],
genusId: json["genus_id"],
id: json["id"],
links: DatumLinks.fromJson(json["links"]),
plantId: json["plant_id"],
rank: json["rank"],
scientificName: json["scientific_name"],
slug: json["slug"],
status: json["status"],
synonyms: List<String>.from(json["synonyms"].map((x) => x)),
year: json["year"],
);
Map<String, dynamic> toJson() => {
"author": author,
"bibliography": bibliography,
"common_name": commonName,
"family": family,
"family_common_name": familyCommonName == null ? null : familyCommonName,
"genus": genus,
"genus_id": genusId,
"id": id,
"links": links.toJson(),
"plant_id": plantId,
"rank": rank,
"scientific_name": scientificName,
"slug": slug,
"status": status,
"synonyms": List<dynamic>.from(synonyms.map((x) => x)),
"year": year,
};
}
class DatumLinks {
DatumLinks({
this.genus,
this.plant,
this.self,
});
String genus;
String plant;
String self;
factory DatumLinks.fromJson(Map<String, dynamic> json) => DatumLinks(
genus: json["genus"],
plant: json["plant"],
self: json["self"],
);
Map<String, dynamic> toJson() => {
"genus": genus,
"plant": plant,
"self": self,
};
}
class PlantLinks {
PlantLinks({
this.first,
this.last,
this.next,
this.self,
});
String first;
String last;
String next;
String self;
factory PlantLinks.fromJson(Map<String, dynamic> json) => PlantLinks(
first: json["first"],
last: json["last"],
next: json["next"],
self: json["self"],
);
Map<String, dynamic> toJson() => {
"first": first,
"last": last,
"next": next,
"self": self,
};
}
class Meta {
Meta({
this.total,
});
int total;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
total: json["total"],
);
Map<String, dynamic> toJson() => {
"total": total,
};
}
response = await http.get(url);
final plant = plantFromJson(response.body) // to get parsed data

Here what i want to say exactly
Future<Plant> fetchData(String url) async {
final response = await http.get(
"TYPE_YOUR_HTTP",
if (response.statusCode == 200) {
return Plant.fromJson(jsonDecode(response.body));//change here
} else {
throw Exception("Failed to load data");
}
}
//Future Builder
Future<Plant> plantList;
plantList = FetchData.fetchdata(data);//create a future object and call your fetch data funct with it
return FutureBuilder<Plant>(
future: plantList,/
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.data == null) {
return Center(
child: Text("No result "),
);
} else {
return ListView.builder(
itemCount: snapshot.data.plant.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
//Create ListTile here or something that you prefer);
},
);
}
} else if (snapshot.connectionState == ConnectionState.none) {
return Center(child: Text(snapshot.error));
} else {
return Center(child: CircularProgressIndicator());
}
});

Related

could not create an instance of type microsoft.aspnetcore.http.iformfile

I am fighting with this error for the last 3 days when I bind the value serImg on imgFile react app then it's showing this error
[Route("PotService")]
[HttpPost]
public async Task<IActionResult> Post( [FromBody] ServiceInfo service)
{
MemoryStream stream = new MemoryStream(service.Data);
IFormFile file = new FormFile(stream, 0, service.Data.Length, "test", "test");
//service.serImg = file;
////string uploads1 = _hostingEnvironment.WebRootPath;
//string uploads = Path.Combine( "Images");
// if (file.Length > 0)
// {
// string filePath = Path.Combine(uploads, service.serImg.FileName);
// using (Stream fileStream = new FileStream(filePath, FileMode.Create))
// {
// service.serImg.CopyToAsync(fileStream);
// }
// }
bool result = _serManager.AddService(service);
return Ok(true);
}
It's used for a react app the code is
const onSubmit = async (data) => {
data.CompanyInfoId = activeComId;
data.imgFile = data.serImg;
data.serType = data.serType.value;
data.serviceClose = data.serviceClose.value;
data.location = data.location.value;
console.log(data);
// console.log(data.serImg..value);
console.log(data.serviceClose.value);
const res = await fetch(serPost, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-type': 'application/JSON; carset=UTF-8',
},
});

Flutter - nested json from API

I am still new to flutter development and recently I've been trying to call API. I've managed to do so without placing data into the model and it worked fine. The issue is when I try to serialize the data. I've created a model using webinovers
https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3
json data
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
here is my code
problem_models
class AllProblem {
late List<Problem>? problems;
AllProblem({this.problems});
AllProblem.fromJson(Map<dynamic, dynamic> json) {
if (json['problems'] != null) {
problems = <Problem>[];
json['problems'].forEach((v) { problems!.add( Problem.fromJson(v)); });
}
}
}
class Problem {
late List<Diabete> diabetes;
late List<Asthma> asthma;
Problem.fromJson(Map<dynamic, dynamic> json) {
if (json['Diabetes'] != null) {
diabetes = <Diabete>[];
json['Diabetes'].forEach((v) { diabetes.add( Diabete.fromJson(v)); });
}
if (json['Asthma'] != null) {
asthma = <Asthma>[];
json['Asthma'].forEach((v) { asthma.add( Asthma.fromJson(v)); });
}
}
}
class Diabete {
late List<Medication> medications;
late List<Labs> labs;
Diabete.fromJson(Map<dynamic, dynamic> json) {
if (json['medications'] != null) {
medications = <Medication>[];
json['medications'].forEach((v) { medications.add( Medication.fromJson(v)); });
}
if (json['labs'] != null) {
labs = <Labs>[];
json['labs'].forEach((v) { labs.add( Labs.fromJson(v)); });
}
}
}
class Medication {
late List<MedicationsClass> medicationsClasses;
Medication.fromJson(Map<dynamic, dynamic> json) {
if (json['medicationsClasses'] != null) {
medicationsClasses = <MedicationsClass>[];
json['medicationsClasses'].forEach((v) { medicationsClasses.add( MedicationsClass.fromJson(v)); });
}
}
}
class MedicationsClass {
late List<ClassName> className;
late List<ClassName> className2;
MedicationsClass.fromJson(Map<dynamic, dynamic> json) {
if (json['className'] != null) {
className = <ClassName>[];
json['className'].forEach((v) { className.add( ClassName.fromJson(v)); });
}
if (json['className2'] != null) {
className2 = <ClassName>[];
json['className2'].forEach((v) { className2.add( ClassName.fromJson(v)); });
}
}
}
class ClassName {
late List<AssociatedDrug> associatedDrug;
late List<AssociatedDrug> associatedDrug2;
ClassName.fromJson(Map<dynamic, dynamic> json) {
if (json['associatedDrug'] != null) {
associatedDrug = <AssociatedDrug>[];
json['associatedDrug'].forEach((v) { associatedDrug.add( AssociatedDrug.fromJson(v)); });
}
if (json['associatedDrug#2'] != null) {
associatedDrug2 = <AssociatedDrug>[];
json['associatedDrug#2'].forEach((v) { associatedDrug2.add( AssociatedDrug.fromJson(v)); });
}
}
}
class AssociatedDrug {
late String name;
String? dose;
late String strength;
AssociatedDrug.fromJson(Map<dynamic, dynamic> json) {
name = json['name'];
dose = json['dose'];
strength = json['strength'];
}
}
class Labs {
late String missingField;
Labs.fromJson(Map<dynamic, dynamic> json) {
missingField = json['missing_field'];
}
}
class Asthma {
Asthma();
Asthma.fromJson(Map<dynamic, dynamic> json) {
}
Map<dynamic, dynamic> toJson() {
final Map<dynamic, dynamic> data = <dynamic, dynamic>{};
return data;
}
}
resposiory_problem
import 'package:mvvp_simple/model/problems_model.dart';
abstract class ProblemsRepository{
Future<List<AllProblem>> getAllProblem();
}
this is resposiory_problem_API
import 'dart:convert';
import 'package:mvvp_simple/model/problems_model.dart';
import 'package:mvvp_simple/repository/problem/problems_repository.dart';
import 'package:http/http.dart' as http;
class ProblemsAPI extends ProblemsRepository{
//late AllProblem allProblem;
#override
Future<List<AllProblem>> getAllProblem() async{
List<AllProblem> problemList =[];
var apiURl = 'https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3';
var response = await http.get(Uri.parse(apiURl));
if (response.statusCode == 200) {
var data = await jsonDecode(response.body.toString());
problemList = data.map((problems)=> AllProblem.fromJson(problems));
for(Map i in data){
problemList.add(AllProblem.fromJson(i));
}
print(problemList);
}
return problemList;
}
}
widget to fetch data
child: FutureBuilder(
future: HomeViewModel().fetchAllProblem(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Loading();
} else {
print('this data loaded ${snapshot.data}' );
var problems = snapshot.data;
return Center(
child: ListView.builder(
itemCount: problems?.length,
itemBuilder: (context, index) => const ListTile(title: Text('Problem'),subtitle: Text('Medications'),),
));
}
},
))

FormControl not patching values to multiple select

I'm working on a angular application but I ran into a problem I cant find the solution to. I'm trying to patch some preselected values to a form control (mat-select multiple) but it just wont show the values. It works fine with the control above (food), but when I try to bind to the multiple choice list, the values wont show.
//Here is my code:
#Component({
selector: 'app-add-edit',
templateUrl: './add-edit.component.html',
styleUrls: ['./add-edit.component.less']
})
export class AddEditComponent implements OnInit {
pageTitle = '';
order: Order;
filteredUsers: User[] = [];
id: number;
orderToDisplay: Order = new Order();
orderForm: FormGroup = new FormGroup({
food: new FormControl('', [Validators.required]),
usersOrdering: new FormControl('', [Validators.required])
});
constructor(private dialogRef: MatDialogRef<AddEditComponent>,
private ordersService: OrdersService,
#Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder) { }
usersSelected: User[];
ngOnInit(): void {
this.id = this.data.orderId;
if (this.id == 0) {
this.pageTitle = 'Add a new order';
this.order = new Order();
} else {
this.pageTitle = 'Edit the order';
this.getOrder(this.id);
}
this.filterUsers(this.id);
}
save(): void {
if (this.orderForm.valid) {
if (this.orderForm.dirty) {
this.usersSelected = this.orderForm.controls['usersOrdering'].value;
if (this.id == 0) {
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.restaurantId = this.data.restaurantId;
this.order.usersOrdering = this.usersSelected;
this.ordersService.addOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
} else {
this.order.id = this.id;
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.usersOrdering = this.usersSelected;
this.ordersService.updateOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
}
}
} else
console.log('form is invalid')
}
dismiss(): void {
this.dialogRef.close(false);
}
displayOrder(o: Order): void {
if (this.orderForm) {
this.orderForm.reset();
}
this.order = o;
console.log(this.order.usersOrdering);
this.orderForm.patchValue({
food: this.order.food,
usersOrdering: this.order.usersOrdering
});
this.orderForm.updateValueAndValidity();
}
filterUsers(orderId: number) {
this.ordersService.filterUsers(orderId)
.subscribe(data => {
this.filteredUsers = data;
});
}
getOrder(id: number) {
this.ordersService.getOrder(id)
.subscribe(data => {
this.order = data;
this.displayOrder(this.order);
});
}

Flutter: How to JSON parse objects inside an object which is inside a List

I have to parse the following json to a data model in flutter
[
{
"cmb_marital_status": {
"1": "Unmarried",
"2": " Married",
"3": " Widow",
"4": " Divorced",
"5": " Separated",
"6": " Living together"
},
"cmb_gender": {
"M": "Male",
"F": "Female"
},
"cmb_yes/no": {
"1": "No",
"2": " Yes"
}
}]
And I have created this data model to parse from the API request.
class AllData {
CmbMaritalStatus cmbMaritalStatus;
CmbGender cmbGender;
CmbYesNo cmbYesNo;
AllData(
{this.cmbMaritalStatus,
this.cmbGender,
this.cmbYesNo});
AllData.fromJson(Map<String, dynamic> json) {
cmbMaritalStatus = json['cmb_marital_status'] != null
? new CmbMaritalStatus.fromJson(json['cmb_marital_status'])
: null;
cmbGender = json['cmb_gender'] != null
? new CmbGender.fromJson(json['cmb_gender'])
: null;
cmbYesNo = json['cmb_yes/no'] != null
? new CmbYesNo.fromJson(json['cmb_yes/no'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cmbMaritalStatus != null) {
data['cmb_marital_status'] = this.cmbMaritalStatus.toJson();
}
if (this.cmbGender != null) {
data['cmb_gender'] = this.cmbGender.toJson();
}
if (this.cmbYesNo != null) {
data['cmb_yes/no'] = this.cmbYesNo.toJson();
}
return data;
}
}
class CmbMaritalStatus {
String s1;
String s2;
String s3;
String s4;
String s5;
String s6;
CmbMaritalStatus({this.s1, this.s2, this.s3, this.s4, this.s5, this.s6});
CmbMaritalStatus.fromJson(Map<String, dynamic> json) {
s1 = json['1'];
s2 = json['2'];
s3 = json['3'];
s4 = json['4'];
s5 = json['5'];
s6 = json['6'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['1'] = this.s1;
data['2'] = this.s2;
data['3'] = this.s3;
data['4'] = this.s4;
data['5'] = this.s5;
data['6'] = this.s6;
return data;
}
}
class CmbGender {
String m;
String f;
CmbGender({this.m, this.f});
CmbGender.fromJson(Map<String, dynamic> json) {
m = json['M'];
f = json['F'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['M'] = this.m;
data['F'] = this.f;
return data;
}
}
class CmbYesNo {
String s1;
String s2;
CmbYesNo({this.s1, this.s2});
CmbYesNo.fromJson(Map<String, dynamic> json) {
s1 = json['1'];
s2 = json['2'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['1'] = this.s1;
data['2'] = this.s2;
return data;
}
}
}
And I am using this API request code to parse data to the data model.
Future <List<AllData>> getAllData(context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final authToken = prefs.getString('accessToken');
List<AllData> data;
try{
final response = await http.get(GET_ALL_DATA,
headers: {
HttpHeaders.contentTypeHeader:"application/json",
HttpHeaders.authorizationHeader: authToken
},
);
var responseBody = json.decode(response.body);
print("all data response: $responseBody");
if(response.statusCode == 200){
var list = json.decode(responseBody[0]) as List;
data = list.map((i)=> AllData.fromJson(i)).toList();
return data;
}else if(response.statusCode == 400 || response.statusCode == 404 || response.statusCode == 401){
Toast.show("Server error",context,backgroundColor: Colors.red,textColor: Colors.white);
}else if (response.statusCode == 500){
Toast.show("Server error",context,backgroundColor: Colors.red,textColor: Colors.white);
}else{
Toast.show("Server error",context,backgroundColor: Colors.red,textColor: Colors.white);
}
}catch (e){
Toast.show("Server error",context,backgroundColor: Colors.red,textColor: Colors.white);
}
return data;
}
But it is returning this error "type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'"
How can I parse this json successfully?
Try to get list from responseBody directly:
final responseBody = json.decode(response.body);
print("all data response: $responseBody");
if(response.statusCode == 200) {
data = responseBody.map((i)=> AllData.fromJson(i)).toList();
return data;
}
First, you already decoded response.body once and you do not need to do it again. Second, responseBody is already List so your code should look like
data = responseBody.map((i)=> AllData.fromJson(i)).toList();
return data;

Not able to get the data from the JSON to fields in flutter

I am able to fetch the JSON data from the server in the flutter application. I need to display the data in PageView.builder and nested ListView.builder, this model I have already created.
The code called for implementation
orderdetail = NewOrder.fromJson(json.decode(response.body));
This is the JSON data which I am able to fetch from the server in flutter application
{
"error": "false",
"content": [
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "16",
"order_items": [
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "16",
},
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "16",
}
]
},
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "18",
"order_items": [
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "18",
},
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "18",
},
{
"comp_code": "4",
"comp_name": "KMT OVERSEAS",
"order_no": "18",
},
]
}
]
}
The code I used for it is this for fetching the data in the Stateful Widget
Future<Payload> getdetailsoforders(String userid, String companycode) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map data = {
'user_id': userid,
'company_code':companycode
};
var response = await http.post(newapi, body: data);
if(response.statusCode == 200) {
jsonResponse = json.decode(response.body);
print("jsonrespnse");
print(jsonResponse);
}
} else {
setState(() {
_isLoading = false;
});
print('login error');
print(response.body);
}
}
The NewOrder Model class I am implemented is below
import 'newitem.dart';
class NewOrder {
NewOrder({
this.sohPk,
this.orderNo,
this.newItem,
});
String sohPk;
String orderNo;
NewItem newItem;
factory NewOrder.fromJson(Map<String, dynamic> json) => NewOrder(
sohPk: json["soh_pk"],
orderNo: json["order_no"],
newItem:NewItem.fromJson(json['order_items'])
);
Map<String, dynamic> toJson() => {
"soh_pk": sohPk,
"order_no": orderNo,
'order_items': newItem.toJson()
};
}
The NewPlayLoadClass I Implemented is here
import 'package:dataproject2/newmodel/neworder.dart';
class NewPayLoad {
String error;
List<NewOrder> content;
NewPayLoad({this.error, this.content});
NewPayLoad.fromJson(Map<String, dynamic> json) {
error = json['error'];
if (json['content'] != null) {
content = new List<NewOrder>();
json['content'].forEach((v) {
content.add(new NewOrder.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
if (this.content != null) {
data['content'] = this.content.map((v) => v.toJson()).toList();
}
return data;
}
}
The error I am getting is here
The following NoSuchMethodError was thrown building
PageViewClass(dirty, state: _PageViewClassState#98a84): The getter
'content' was called on null. Receiver: null Tried calling: content
I am not able to understand what is wrong with my code, and how to resolve it
Please guide further
Use below code
class NewOrder {
String _error;
List<Content> _content;
NewOrder({String error, List<Content> content}) {
this._error = error;
this._content = content;
}
String get error => _error;
set error(String error) => _error = error;
List<Content> get content => _content;
set content(List<Content> content) => _content = content;
NewOrder.fromJson(Map<String, dynamic> json) {
_error = json['error'];
if (json['content'] != null) {
_content = new List<Content>();
json['content'].forEach((v) {
_content.add(new Content.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this._error;
if (this._content != null) {
data['content'] = this._content.map((v) => v.toJson()).toList();
}
return data;
}
}
class Content {
String _compCode;
String _compName;
String _orderNo;
List<OrderItems> _orderItems;
Content(
{String compCode,
String compName,
String orderNo,
List<OrderItems> orderItems}) {
this._compCode = compCode;
this._compName = compName;
this._orderNo = orderNo;
this._orderItems = orderItems;
}
String get compCode => _compCode;
set compCode(String compCode) => _compCode = compCode;
String get compName => _compName;
set compName(String compName) => _compName = compName;
String get orderNo => _orderNo;
set orderNo(String orderNo) => _orderNo = orderNo;
List<OrderItems> get orderItems => _orderItems;
set orderItems(List<OrderItems> orderItems) => _orderItems = orderItems;
Content.fromJson(Map<String, dynamic> json) {
_compCode = json['comp_code'];
_compName = json['comp_name'];
_orderNo = json['order_no'];
if (json['order_items'] != null) {
_orderItems = new List<OrderItems>();
json['order_items'].forEach((v) {
_orderItems.add(new OrderItems.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['comp_code'] = this._compCode;
data['comp_name'] = this._compName;
data['order_no'] = this._orderNo;
if (this._orderItems != null) {
data['order_items'] = this._orderItems.map((v) => v.toJson()).toList();
}
return data;
}
}
class OrderItems {
String _compCode;
String _compName;
String _orderNo;
OrderItems({String compCode, String compName, String orderNo}) {
this._compCode = compCode;
this._compName = compName;
this._orderNo = orderNo;
}
String get compCode => _compCode;
set compCode(String compCode) => _compCode = compCode;
String get compName => _compName;
set compName(String compName) => _compName = compName;
String get orderNo => _orderNo;
set orderNo(String orderNo) => _orderNo = orderNo;
OrderItems.fromJson(Map<String, dynamic> json) {
_compCode = json['comp_code'];
_compName = json['comp_name'];
_orderNo = json['order_no'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['comp_code'] = this._compCode;
data['comp_name'] = this._compName;
data['order_no'] = this._orderNo;
return data;
}
}

Resources