How can I extract uniqued caterogies from JSON in Flutter? - json

I have a JSON
[{"id":495, "title":"BSB", "category":null},{"id":495, "title":"BCB", "category":"temp"},{"id":495, "title":"BSB", "category":"temp"},{"id":495, "title":"BSB", "category":"cat12"},...]
I want to extract uniqued categories in a list without contain null value in Flutter. Example: List ["temp","cat12"...]
How to use model to fetch the categories from JSON?
Thanks in advance.
My current model.dart:
List<Product> productFromJson(String str) => List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));
String productToJson(List<Product> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Product {
Product({
this.id,
this.title,
this.category,
});
int id;
String title;
String category;
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json["id"],
title: json["title"],
category: json["category"] == null ? null : json["category"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"category": category == null ? null : category,
};
}

// #dart=2.12
void doSomething() {
var list = [{"id":495, "title":"BSB", "category":null},{"id":495, "title":"BCB", "category":"temp"},{"id":495, "title":"BSB", "category":"temp"},{"id":495, "title":"BSB", "category":"cat12"}];
var myList = list.map((m) => m['category']).toSet().where((e) => e != null);
print(myList);
}
void main() {
doSomething();
}
Result:
(temp, cat12)

Related

convert it to list flutter firebase

this is my database image
import 'dart:convert';
class ReviewcountInfo{
List<String> uid;
ReviewcountInfo({
required this.uid,
})
List<String> toList() {
return
}
factory ReviewcountInfo.fromMap(Map<String, dynamic> map) {
return ReviewcountInfo(
uid: ['uid'] ?? 0,
);}
String toJson() => json.encode(toList());
factory ReviewcountInfo.fromJson(String source) =>
ReviewcountInfo.fromMap(json.decode(source));
}
I want to get data in the form of an array from firebase, how can I get it?
I don't know how to fill 'List toList()','factory ReviewcountInfo' part.
class BrandingInfo {
num price;
BrandingInfo({
required this.price,
});
Map<String, dynamic> toMap() {
return {
'price': price,
};
}
factory BrandingInfo.fromMap(Map<String, dynamic> map) {
return BrandingInfo(
price: map['price'] ?? 0,
);
}
String toJson() => json.encode(toMap());
factory BrandingInfo.fromJson(String source) =>
BrandingInfo.fromMap(json.decode(source));
}
this is my example Code
I am coding by referring to the code above.
try this model
import 'dart:convert';
List<ReviewCount> reviewCountFromJson(String str) => List<ReviewCount>.from(json.decode(str).map((x) => ReviewCount.fromJson(x)));
String reviewCountToJson(List<ReviewCount> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ReviewCount {
ReviewCount({
this.reviewcount,
});
final Reviewcount? reviewcount;
factory ReviewCount.fromJson(Map<String, dynamic> json) => ReviewCount(
reviewcount: json["reviewcount"] == null ? null : Reviewcount.fromJson(json["reviewcount"]),
);
Map<String, dynamic> toJson() => {
"reviewcount": reviewcount == null ? null : reviewcount.toJson(),
};
}
class Reviewcount {
Reviewcount({
this.uid,
});
final List<String>? uid;
factory Reviewcount.fromJson(Map<String, dynamic> json) => Reviewcount(
uid: json["uid"] == null ? null : List<String>.from(json["uid"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"uid": uid == null ? null : List<dynamic>.from(uid!.map((x) => x)),
};
}
then for getting the data from firestore
Future<Reviewcount> getuidList({String? pathDocuid}) async{
final response = await FirebaseFirestore.instance.collection("service").doc(pathDocuid!).get();
final mapItFirst = response.data() as Map<String,dynamic>;
// but first print the data using log so you can see if it
// gettingdata
log("${mapItFirst['reviewcount']}");
log("${mapItFirst['reviewcount']['uid']}");
return Reviewcount.fromJson(mapItFirst["reviewcount"]);
}
try this if it works if not mention me.

Why can't i get data value from json - flutter

Am trying to get values from my json file categories.json using flutter but am always getting error or its not showing and I don't really know what is wrong
This is my main.dart
Future<List<Category>> loadData() async {
String jString = await rootBundle.loadString("assets/categories.json");
List<dynamic> jRes = jsonDecode(jString);
List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();
return datas;
}
Container(
child: FutureBuilder<List<Category>>(
future: loadData(),
builder: (context, data) {
if (data.connectionState != ConnectionState.waiting &&
data.hasData) {
var userList = data.data;
return ListView.builder(
itemCount: userList.length,
itemBuilder: (context, index) {
var userData = userList[index];
return Column(
children: [
Text("Category: ${userData.catName}"),
],
);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})),
and my model.dart
class Category {
String catId;
String catName;
SubCategory subcat;
Category({this.catId, this.catName, this.subcat});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
catId: json['cat_id'],
catName: json['category'],
subcat: SubCategory.fromJson(json['cat_subcategory']),
);
}
Map<String, dynamic> toJson() {
return {
"cat_id": catId,
"category": catName,
};
}
}
class SubCategory {
String subName, subImage;
SubCategory({this.subName, this.subImage});
factory SubCategory.fromJson(Map<String, dynamic> json) {
return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
}
Map<String, dynamic> toJson() {
return {
"sub_name": subName,
"sub_image": subImage,
};
}
}
and lastly my categories.json file
[{
"category": "Design & Creativity",
"cat_id": "1",
"cat_subcategory": [
{
"sub_name": "Ads",
"sub_image": "https://images.unsplash.com/photo-1589838017489-9198a27bd040?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8YWR2ZXJ0aXNlbWVudHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
]
}]
//There are more of them
The problem am facing when I run it is that it only shows me the CircularProgressIndicator() in my main.dart and when I remove the if statement, it says Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null. Please how do I go about solving this problem and if you need more explanation then tell me
PS: When I check the loadData() value it says type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
EDIT: Thank you all for the answers but what i did was to generate a model using this website model generator
and i was able to get the value
Personally, when I want to load data from json file, I do this:
Future<List<Category>> loadData() async {
List<Category> datas = [];
return rootBundle.loadString("assets/categories.json").then((value) {
List<dynamic> jRes = jsonDecode(value);
jRes.forEach((element) {
datas.add(Category.fromJson(element));
});
return datas;
});
}
Also, in SubCategory class
factory SubCategory.fromJson(Map<String, dynamic> json) {
return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
}
Your fromJson() require Map<String, dynamic>.
But if you look at your file
"cat_subcategory": [
{
"sub_name": "Ads",
"sub_image": "https://images.unsplash.com/photo-1589838017489-9198a27bd040?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8YWR2ZXJ0aXNlbWVudHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
]
You can see that cat_subcategory is a List
So you are giving a List to your SubCategory.fromJson() instead of a Map.
If you want to give a Map, you can simply give the first index of your list
Your Category.fromJson() become
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
catId: json['cat_id'],
catName: json['category'],
subcat: SubCategory.fromJson(json['cat_subcategory'][0]),
);
}
Change your model.dart class
class Category {
String category;
String catId;
List<CatSubcategory> catSubcategory;
Category({this.category, this.catId, this.catSubcategory});
Category.fromJson(Map<String, dynamic> json) {
category = json['category'];
catId = json['cat_id'];
if (json['cat_subcategory'] != null) {
catSubcategory = new List<CatSubcategory>();
json['cat_subcategory'].forEach((v) {
catSubcategory.add(new CatSubcategory.fromJson(v));
});
}}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['category'] = this.category;
data['cat_id'] = this.catId;
if (this.catSubcategory != null) {
data['cat_subcategory'] =
this.catSubcategory.map((v) => v.toJson()).toList();
}
return data;
}}
class CatSubcategory {
String subName;
String subImage;
CatSubcategory({this.subName, this.subImage});
CatSubcategory.fromJson(Map<String, dynamic> json) {
subName = json['sub_name'];
subImage = json['sub_image'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sub_name'] = this.subName;
data['sub_image'] = this.subImage;
return data;
}}
And Replace
List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();
with
List<Category> datas = List<Category>.from(jRes.map((category)=> Category.fromJson(category)));

Unable to load json data from the internet due to a subtyp error : List<dynamic> is not type Map<String,Dymanic>

I'm new to flutter and I want to fetch json data from an API. I'm using json serializable.
this is my code where I fetch the data from the internet:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_json_widget/flutter_json_widget.dart';
import './JsonDataMeter.dart';
Future<Meter> fetchMeter() async {
final response = await http.get(
'the url');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Meter.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load meter');
}
}
class MeterList extends StatefulWidget {
MeterList({Key key, }) : super(key: key);
#override
_MeterList createState() => _MeterList();
}
class _MeterList extends State<MeterList> {
Future<Meter> futureMeter;
#override
void initState(){
super.initState();
futureMeter = fetchMeter();
}
#override
Widget build(BuildContext context) {
return FutureBuilder<Meter>(
future: futureMeter,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.address.city);
} else if (snapshot.hasError) {
//return Text("${snapshot.error}");
print(snapshot.error);
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
);
}
This is where I create the classes, which contain the json data:
import 'package:json_annotation/json_annotation.dart';
part 'JsonDataMeter.g.dart';
#JsonSerializable(explicitToJson: true)
class Meter{
Address address;
List<Apartments> apartments;
Meter({this.address, this.apartments});
factory Meter.fromJson(Map<String,dynamic> json) => _$MeterFromJson(json);
Map<String,dynamic> toJson() => _$MeterToJson(this);
}
#JsonSerializable()
class Address {
String streetAndNumber;
int PLZ;
String city;
Address({this.streetAndNumber, this.PLZ, this.city});
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
Map<String,dynamic> toJson() => _$AddressToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Apartments{
Tenants tenants;
List<AssignedMeter> assignedMeter;
String id;
Meters meters;
String location;
int area;
String belongingProperty;
int v;
Apartments({this.tenants,this.assignedMeter, this.id, this.meters, this.location, this.area, this.belongingProperty, this.v});
factory Apartments.fromJson(Map<String,dynamic> json) => _$ApartmentsFromJson(json);
Map<String,dynamic> toJson() => _$ApartmentsToJson(this);
}
#JsonSerializable()
class Tenants{
String id;
String name;
String belongingApartment;
String timeInApartment;
int prepayment;
int v;
UsageTimes usageTimes;
AssociatedApartments associatedApartments;
Tenants({this.id,this.name, this.belongingApartment, this.timeInApartment, this.prepayment, this.v, this.usageTimes, this.associatedApartments});
factory Tenants.fromJson(Map<String,dynamic> json) => _$TenantsFromJson(json);
Map<String,dynamic> toJson() => _$TenantsToJson(this);
}
#JsonSerializable()
class UsageTimes{
String id;
String usageTime;
int usedArea;
UsageTimes({this.id, this.usageTime, this.usedArea});
factory UsageTimes.fromJson(Map<String,dynamic> json) => _$UsageTimesFromJson(json);
Map<String,dynamic> toJson() => _$UsageTimesToJson(this);
}
#JsonSerializable()
class AssociatedApartments{
UsageTimes usageTimes;
String id;
String apartmentID;
String timeInApartment;
AssociatedApartments({this.usageTimes, this.id, this.apartmentID, this.timeInApartment});
factory AssociatedApartments.fromJson(Map<String,dynamic> json) => _$AssociatedApartmentsFromJson(json);
Map<String,dynamic> toJson() => _$AssociatedApartmentsToJson(this);
}
#JsonSerializable()
class AssignedMeter{
String id;
MeterReadings meterReadings;
String belongingApartment;
String meterNumber;
String meterType;
int v;
AssignedMeter({this.id, this.meterReadings, this.belongingApartment, this.meterNumber, this.meterType, this.v});
factory AssignedMeter.fromJson(Map<String,dynamic> json) => _$AssignedMeterFromJson(json);
Map<String,dynamic> toJson() => _$AssignedMeterToJson(this);
}
#JsonSerializable()
class MeterReadings {
String id;
String date;
String value;
MeterReadings({this.id, this.date, this.value});
factory MeterReadings.fromJson(Map<String,dynamic> json) => _$MeterReadingsFromJson(json);
Map<String,dynamic> toJson() => _$MeterReadingsToJson(this);
}
#JsonSerializable()
class Meters{
String id;
String dateStart;
String dateEnd;
int waterStart;
int waterEnd;
int powerStart;
int powerEnd;
Meters({this.id, this.dateStart, this.dateEnd, this.waterStart, this.waterEnd, this.powerStart, this.powerEnd});
factory Meters.fromJson(Map<String,dynamic> json) => _$MetersFromJson(json);
Map<String,dynamic> toJson() => _$MetersToJson(this);
}
And this the auto generated code from JsonSerializable:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'JsonDataMeter.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Meter _$MeterFromJson(Map<String, dynamic> json) {
return Meter(
address: json['address'] == null
? null
: Address.fromJson(json['address'] as Map<String, dynamic>),
apartments: (json['apartments'] as List)
?.map((e) =>
e == null ? null : Apartments.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$MeterToJson(Meter instance) => <String, dynamic>{
'address': instance.address,
'apartments': instance.apartments,
};
Address _$AddressFromJson(Map<String, dynamic> json) {
return Address(
streetAndNumber: json['streetAndNumber'] as String,
PLZ: json['PLZ'] as int,
city: json['city'] as String,
);
}
Map<String, dynamic> _$AddressToJson(Address instance) => <String, dynamic>{
'streetAndNumber': instance.streetAndNumber,
'PLZ': instance.PLZ,
'city': instance.city,
};
Apartments _$ApartmentsFromJson(Map<String, dynamic> json) {
return Apartments(
tenants: json['tenants'] == null
? null
: Tenants.fromJson(json['tenants'] as Map<String, dynamic>),
assignedMeter: (json['assignedMeter'] as List)
?.map((e) => e == null
? null
: AssignedMeter.fromJson(e as Map<String, dynamic>))
?.toList(),
id: json['id'] as String,
meters: json['meters'] == null
? null
: Meters.fromJson(json['meters'] as Map<String, dynamic>),
location: json['location'] as String,
area: json['area'] as int,
belongingProperty: json['belongingProperty'] as String,
v: json['v'] as int,
);
}
Map<String, dynamic> _$ApartmentsToJson(Apartments instance) =>
<String, dynamic>{
'tenants': instance.tenants,
'assignedMeter': instance.assignedMeter,
'id': instance.id,
'meters': instance.meters,
'location': instance.location,
'area': instance.area,
'belongingProperty': instance.belongingProperty,
'v': instance.v,
};
Tenants _$TenantsFromJson(Map<String, dynamic> json) {
return Tenants(
id: json['id'] as String,
name: json['name'] as String,
belongingApartment: json['belongingApartment'] as String,
timeInApartment: json['timeInApartment'] as String,
prepayment: json['prepayment'] as int,
v: json['v'] as int,
usageTimes: json['usageTimes'] == null
? null
: UsageTimes.fromJson(json['usageTimes'] as Map<String, dynamic>),
associatedApartments: json['associatedApartments'] == null
? null
: AssociatedApartments.fromJson(
json['associatedApartments'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$TenantsToJson(Tenants instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'belongingApartment': instance.belongingApartment,
'timeInApartment': instance.timeInApartment,
'prepayment': instance.prepayment,
'v': instance.v,
'usageTimes': instance.usageTimes,
'associatedApartments': instance.associatedApartments,
};
UsageTimes _$UsageTimesFromJson(Map<String, dynamic> json) {
return UsageTimes(
id: json['id'] as String,
usageTime: json['usageTime'] as String,
usedArea: json['usedArea'] as int,
);
}
Map<String, dynamic> _$UsageTimesToJson(UsageTimes instance) =>
<String, dynamic>{
'id': instance.id,
'usageTime': instance.usageTime,
'usedArea': instance.usedArea,
};
AssociatedApartments _$AssociatedApartmentsFromJson(Map<String, dynamic> json) {
return AssociatedApartments(
usageTimes: json['usageTimes'] == null
? null
: UsageTimes.fromJson(json['usageTimes'] as Map<String, dynamic>),
id: json['id'] as String,
apartmentID: json['apartmentID'] as String,
timeInApartment: json['timeInApartment'] as String,
);
}
Map<String, dynamic> _$AssociatedApartmentsToJson(
AssociatedApartments instance) =>
<String, dynamic>{
'usageTimes': instance.usageTimes,
'id': instance.id,
'apartmentID': instance.apartmentID,
'timeInApartment': instance.timeInApartment,
};
AssignedMeter _$AssignedMeterFromJson(Map<String, dynamic> json) {
return AssignedMeter(
id: json['id'] as String,
meterReadings: json['meterReadings'] == null
? null
: MeterReadings.fromJson(json['meterReadings'] as Map<String, dynamic>),
belongingApartment: json['belongingApartment'] as String,
meterNumber: json['meterNumber'] as String,
meterType: json['meterType'] as String,
v: json['v'] as int,
);
}
Map<String, dynamic> _$AssignedMeterToJson(AssignedMeter instance) =>
<String, dynamic>{
'id': instance.id,
'meterReadings': instance.meterReadings,
'belongingApartment': instance.belongingApartment,
'meterNumber': instance.meterNumber,
'meterType': instance.meterType,
'v': instance.v,
};
MeterReadings _$MeterReadingsFromJson(Map<String, dynamic> json) {
return MeterReadings(
id: json['id'] as String,
date: json['date'] as String,
value: json['value'] as String,
);
}
Map<String, dynamic> _$MeterReadingsToJson(MeterReadings instance) =>
<String, dynamic>{
'id': instance.id,
'date': instance.date,
'value': instance.value,
};
Meters _$MetersFromJson(Map<String, dynamic> json) {
return Meters(
id: json['id'] as String,
dateStart: json['dateStart'] as String,
dateEnd: json['dateEnd'] as String,
waterStart: json['waterStart'] as int,
waterEnd: json['waterEnd'] as int,
powerStart: json['powerStart'] as int,
powerEnd: json['powerEnd'] as int,
);
}
Map<String, dynamic> _$MetersToJson(Meters instance) => <String, dynamic>{
'id': instance.id,
'dateStart': instance.dateStart,
'dateEnd': instance.dateEnd,
'waterStart': instance.waterStart,
'waterEnd': instance.waterEnd,
'powerStart': instance.powerStart,
'powerEnd': instance.powerEnd,
};
Finally this is the json I want to fetch (not the original values):
{
"address": {
"streetAndNumber": "SomeData",
"PLZ": 1,
"city": "SomeData"
},
"apartments": [
{
"tenants": [
{
"_id": "SomeData",
"name": "SomeData",
"belongingApartment": "SomeData",
"timeInApartment": "SomeData",
"prepayment": 1,
"__v": 1,
"usageTimes": [
{
"_id": "SomeData",
"usageTime": "SomeData",
"usedArea": 1
}
],
"associatedApartments": [
{
"usageTimes": [
{
"_id": "SomeData",
"usageTime": "SomeData",
"usedArea": 1
}
],
"_id": "SomeData",
"apartmentID": "SomeData",
"timeInApartment": "SomeData"
}
]
}
],
"assignedMeters": [
{
"_id": "SomeData",
"meterReadings": [
{
"_id": "SomeData",
"date": "SomeData",
"value": 1
}
],
"belongingApartment": "SomeData",
"meterNumber": "SomeData",
"meterType": "SomeData",
"__v": 1
},
{
"_id": "SomeData",
"meterReadings": [
{
"_id": "SomeData",
"date": "SomeData",
"value": 1
}
],
"belongingApartment": "SomeData",
"meterNumber": "SomeData",
"meterType": "SomeData",
"__v": 1
},
{
"_id": "SomeData",
"meterReadings": [
{
"_id": "SomeData",
"date": "SomeData",
"value": 1
},
{
"_id": "SomeData",
"date": "SomeData",
"value": 1
}
],
"belongingApartment": "SomeData",
"meterNumber": "SomeData",
"meterType": "SomeData",
"__v": 1
}
],
"_id": "SomeData",
"meters": [
{
"_id": "SomeData",
"dateStart": "SomeData",
"dateEnd": "SomeData",
"waterStart": 1,
"waterEnd": 1,
"powerStart": 1,
"powerEnd": 1
}
],
"location": "SomeData",
"area": 1,
"belongingProperty": "SomeData",
"__v": 1
},
I always get the Error:
I/flutter ( 4626): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast
As I said I'm new to flutter and it's maybe just a really stupid mistake but please help me, I feel like I tried everything but I just don't know what to do.
Thank you very much.
The issue lies in your Model.
e.g:
In apartment model tenants, meters should be type List<...>.
In tenants model usageTimes, associatedApartments should be type List<..>.
In associatedApartments model usageTimes should be type List<...>.
I have generated a new response model from your json using this link https://javiercbk.github.io/json_to_dart/.
Give it a try.
class MeterListResponse {
Address address;
List<Apartments> apartments;
MeterListResponse({this.address, this.apartments});
MeterListResponse.fromJson(Map<String, dynamic> json) {
address =
json['address'] != null ? new Address.fromJson(json['address']) : null;
if (json['apartments'] != null) {
apartments = new List<Apartments>();
json['apartments'].forEach((v) {
apartments.add(new Apartments.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.address != null) {
data['address'] = this.address.toJson();
}
if (this.apartments != null) {
data['apartments'] = this.apartments.map((v) => v.toJson()).toList();
}
return data;
}
}
class Address {
String streetAndNumber;
int pLZ;
String city;
Address({this.streetAndNumber, this.pLZ, this.city});
Address.fromJson(Map<String, dynamic> json) {
streetAndNumber = json['streetAndNumber'];
pLZ = json['PLZ'];
city = json['city'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['streetAndNumber'] = this.streetAndNumber;
data['PLZ'] = this.pLZ;
data['city'] = this.city;
return data;
}
}
class Apartments {
List<Tenants> tenants;
List<AssignedMeters> assignedMeters;
String sId;
List<Meters> meters;
String location;
int area;
String belongingProperty;
int iV;
Apartments(
{this.tenants,
this.assignedMeters,
this.sId,
this.meters,
this.location,
this.area,
this.belongingProperty,
this.iV});
Apartments.fromJson(Map<String, dynamic> json) {
if (json['tenants'] != null) {
tenants = new List<Tenants>();
json['tenants'].forEach((v) {
tenants.add(new Tenants.fromJson(v));
});
}
if (json['assignedMeters'] != null) {
assignedMeters = new List<AssignedMeters>();
json['assignedMeters'].forEach((v) {
assignedMeters.add(new AssignedMeters.fromJson(v));
});
}
sId = json['_id'];
if (json['meters'] != null) {
meters = new List<Meters>();
json['meters'].forEach((v) {
meters.add(new Meters.fromJson(v));
});
}
location = json['location'];
area = json['area'];
belongingProperty = json['belongingProperty'];
iV = json['__v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.tenants != null) {
data['tenants'] = this.tenants.map((v) => v.toJson()).toList();
}
if (this.assignedMeters != null) {
data['assignedMeters'] =
this.assignedMeters.map((v) => v.toJson()).toList();
}
data['_id'] = this.sId;
if (this.meters != null) {
data['meters'] = this.meters.map((v) => v.toJson()).toList();
}
data['location'] = this.location;
data['area'] = this.area;
data['belongingProperty'] = this.belongingProperty;
data['__v'] = this.iV;
return data;
}
}
class Tenants {
String sId;
String name;
String belongingApartment;
String timeInApartment;
int prepayment;
int iV;
List<UsageTimes> usageTimes;
List<AssociatedApartments> associatedApartments;
Tenants(
{this.sId,
this.name,
this.belongingApartment,
this.timeInApartment,
this.prepayment,
this.iV,
this.usageTimes,
this.associatedApartments});
Tenants.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
belongingApartment = json['belongingApartment'];
timeInApartment = json['timeInApartment'];
prepayment = json['prepayment'];
iV = json['__v'];
if (json['usageTimes'] != null) {
usageTimes = new List<UsageTimes>();
json['usageTimes'].forEach((v) {
usageTimes.add(new UsageTimes.fromJson(v));
});
}
if (json['associatedApartments'] != null) {
associatedApartments = new List<AssociatedApartments>();
json['associatedApartments'].forEach((v) {
associatedApartments.add(new AssociatedApartments.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['name'] = this.name;
data['belongingApartment'] = this.belongingApartment;
data['timeInApartment'] = this.timeInApartment;
data['prepayment'] = this.prepayment;
data['__v'] = this.iV;
if (this.usageTimes != null) {
data['usageTimes'] = this.usageTimes.map((v) => v.toJson()).toList();
}
if (this.associatedApartments != null) {
data['associatedApartments'] =
this.associatedApartments.map((v) => v.toJson()).toList();
}
return data;
}
}
class UsageTimes {
String sId;
String usageTime;
int usedArea;
UsageTimes({this.sId, this.usageTime, this.usedArea});
UsageTimes.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
usageTime = json['usageTime'];
usedArea = json['usedArea'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['usageTime'] = this.usageTime;
data['usedArea'] = this.usedArea;
return data;
}
}
class AssociatedApartments {
List<UsageTimes> usageTimes;
String sId;
String apartmentID;
String timeInApartment;
AssociatedApartments(
{this.usageTimes, this.sId, this.apartmentID, this.timeInApartment});
AssociatedApartments.fromJson(Map<String, dynamic> json) {
if (json['usageTimes'] != null) {
usageTimes = new List<UsageTimes>();
json['usageTimes'].forEach((v) {
usageTimes.add(new UsageTimes.fromJson(v));
});
}
sId = json['_id'];
apartmentID = json['apartmentID'];
timeInApartment = json['timeInApartment'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.usageTimes != null) {
data['usageTimes'] = this.usageTimes.map((v) => v.toJson()).toList();
}
data['_id'] = this.sId;
data['apartmentID'] = this.apartmentID;
data['timeInApartment'] = this.timeInApartment;
return data;
}
}
class AssignedMeters {
String sId;
List<MeterReadings> meterReadings;
String belongingApartment;
String meterNumber;
String meterType;
int iV;
AssignedMeters(
{this.sId,
this.meterReadings,
this.belongingApartment,
this.meterNumber,
this.meterType,
this.iV});
AssignedMeters.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
if (json['meterReadings'] != null) {
meterReadings = new List<MeterReadings>();
json['meterReadings'].forEach((v) {
meterReadings.add(new MeterReadings.fromJson(v));
});
}
belongingApartment = json['belongingApartment'];
meterNumber = json['meterNumber'];
meterType = json['meterType'];
iV = json['__v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
if (this.meterReadings != null) {
data['meterReadings'] =
this.meterReadings.map((v) => v.toJson()).toList();
}
data['belongingApartment'] = this.belongingApartment;
data['meterNumber'] = this.meterNumber;
data['meterType'] = this.meterType;
data['__v'] = this.iV;
return data;
}
}
class MeterReadings {
String sId;
String date;
int value;
MeterReadings({this.sId, this.date, this.value});
MeterReadings.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
date = json['date'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['date'] = this.date;
data['value'] = this.value;
return data;
}
}
class Meters {
String sId;
String dateStart;
String dateEnd;
int waterStart;
int waterEnd;
int powerStart;
int powerEnd;
Meters(
{this.sId,
this.dateStart,
this.dateEnd,
this.waterStart,
this.waterEnd,
this.powerStart,
this.powerEnd});
Meters.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
dateStart = json['dateStart'];
dateEnd = json['dateEnd'];
waterStart = json['waterStart'];
waterEnd = json['waterEnd'];
powerStart = json['powerStart'];
powerEnd = json['powerEnd'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['dateStart'] = this.dateStart;
data['dateEnd'] = this.dateEnd;
data['waterStart'] = this.waterStart;
data['waterEnd'] = this.waterEnd;
data['powerStart'] = this.powerStart;
data['powerEnd'] = this.powerEnd;
return data;
}
}

Not getting required value from json list - flutter

I have this code where am able to get values from an online json data and print its value
main.dart
final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
List<CatSubcategory> subCate = [];
int localInt;
#override
void initState() {
// TODO: implement initState
super.initState();
localInt = 0;
loadData(localInt);
}
loadData(int dataInt) async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
data['cat_subcategory'].map((x) {
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
print(myModel[dataInt].catSubcategory.length);
} else {
print("Something went wrong!");
}
}
my model.dart
class JsonModel {
JsonModel({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(
json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon,
"cat_subcategory":
List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
The only problem am having now is that when I try to print the length on the subcategory of the first list it gives me 24 instead of 6 and i printed it like this myModel[dataInt].catSubcategory.length. The dataInt is 0 which means it's supposed to print out the length of the children("cat_subcategory") with category of Design & Creativity but it's printing all the other children of the other lis. So please how do i go about this. And if you need more explanation tell me
I would avoid writing your own model from scratch if you already know the schema of your json.
Just use something like https://app.quicktype.io/ just paste your json and you will get
import 'dart:convert';
class Root {
Root({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory Root.fromJson(Map<String, dynamic> json) => Root(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"] == null ? null : json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon == null ? null : catIcon,
"cat_subcategory": List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
and then you should be good to just
loadData(int dataInt) async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var list = json.decode(resBody) as List;
List<Root> items = list.map((i)=>Root.fromJson(i)).toList();
print(items[0].catSubcategory.length);
}
} else {
print("Something went wrong!");
}
}
https://repl.it/talk/share/Sample/118111

flutter - type '(dynamic, dynamic) => Null' is not a subtype of type '(dynamic) => dynamic' of 'f'

I just tried parsing data from a firebase realtime database.
but has problems when converting to Model
I'm trying to parse data from the firebase database on Flutter.
But an error said
MY Complete QUIZ: {-M5-R3BqTajbCFk5mQuQ: {coins: 434, isSubmit: true,
questions: [{answer: sddsd, name: Why do we use it?, options:
[established, adwada, adawda, sddsd], select: }, {answer: adawda,
name: Where can I get some?, options: [established, adwada, adawda,
sddsd], select: sddsd}, {answer: adwada, name: Lorem Ipsum is simply
dummy text of the printing?, options: [established, adwada, adawda,
sddsd], select: established}], quizId: YItWgbYjHm},
-M50HhYPnuR7tSC-9ajw: {isSubmit: true, questions: [{answer: dadada, name: Where does it come from?, options: [vvvv, dadada, dsdsdssd,
bbbbbb], select: dadada}], quizId: 9pdzphz0x8}}
I/flutter ( 6768): type '(dynamic, dynamic) => Null' is not a subtype of type '(dynamic) => dynamic' of 'f'
Here, the database structure
The following function for fetchMyQuiz()
Future<Quiz> fetchMyQuiz(String uid) async {
Quiz _quiz;
var dio = Dio();
dio.options
..baseUrl = Constant.baseUrl
..connectTimeout = 5000 //5s
..receiveTimeout = 5000
..validateStatus = (int status) {
return status > 0;
}
..headers = {
HttpHeaders.userAgentHeader: 'dio',
'common-header': 'xx',
};
_isLoadingUser = true;
notifyListeners();
List<Quiz> _fetchedQuiz = [];
try {
var response = await dio.get(
Constant.userParam + '/$uid' + Constant.quiz + Constant.jsonExt,
options: Options(
contentType: Headers.formUrlEncodedContentType,
),
);
print("MY Complete QUIZ: ${response.data}");
if (response.statusCode == 200) {
var responseData = response.data;
responseData.forEach((String id, dynamic json) {
if (responseData != null) {
_quiz = Quiz.fromJson(id, json);
_fetchedQuiz.add(_quiz);
}
});
} else {
print("FETCH QUIZ error: ${response.data}");
}
} catch (e) {
print(e);
}
_myQuizList = _fetchedQuiz;
_isLoadingUser = false;
notifyListeners();
return _quiz;
}
class Quiz {
String id;
String quizId;
int coins;
bool isSubmit;
List<Questions> questions;
Quiz({this.id, this.quizId, this.coins, this.isSubmit, this.questions});
Quiz.fromJson(String idQuiz, Map<String, dynamic> json) {
id = idQuiz;
quizId = json['quizId'];
coins = json['coins'];
isSubmit = json['isSubmit'] == null ? false : json['isSubmit'];
if (json['questions'] != null) {
questions = new List<Questions>();
json['questions'].forEach((idQuest, vQuest) {
questions.add(new Questions.fromJson(idQuest, vQuest));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['quizId'] = this.quizId;
data['coins'] = this.coins;
data['isSubmit'] = this.isSubmit;
if (this.questions != null) {
data['questions'] = this.questions.map((v) => v.toJson()).toList();
}
return data;
}
}
class Questions {
String id;
String name;
String select;
String answer;
// bool isSave;
List<String> options;
Questions(
{this.id,
this.name,
this.select,
this.answer,
// this.isSave,
this.options});
Questions.fromJson(String id, Map<String, dynamic> json) {
id = id;
name = json['name'];
select = json['select'] == null ? '' : json['select'];
answer = json['answer'];
// isSave = false;
if (json['options'] != null) {
options = json['options'].cast<String>();
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['select'] = this.select;
data['answer'] = this.answer;
// data['isSave'] = this.isSave;
data['options'] = this.options;
return data;
}
}
Any answer will appretiated.
I think your problem is in your parsing process. I used quicktype to generate your models. check them below
class Quiz {
final int coins;
final bool isSubmit;
final List<Question> questions;
final String quizId;
Quiz({
this.coins,
this.isSubmit,
this.questions,
this.quizId,
});
Quiz copyWith({
int coins,
bool isSubmit,
List<Question> questions,
String quizId,
}) =>
Quiz(
coins: coins ?? this.coins,
isSubmit: isSubmit ?? this.isSubmit,
questions: questions ?? this.questions,
quizId: quizId ?? this.quizId,
);
factory Quiz.fromRawJson(String str) => Quiz.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Quiz.fromJson(Map<String, dynamic> json) => Quiz(
coins: json["coins"] == null ? null : json["coins"],
isSubmit: json["isSubmit"] == null ? null : json["isSubmit"],
questions: json["questions"] == null ? null : List<Question>.from(json["questions"].map((x) => Question.fromJson(x))),
quizId: json["quizId"] == null ? null : json["quizId"],
);
Map<String, dynamic> toJson() => {
"coins": coins == null ? null : coins,
"isSubmit": isSubmit == null ? null : isSubmit,
"questions": questions == null ? null : List<dynamic>.from(questions.map((x) => x.toJson())),
"quizId": quizId == null ? null : quizId,
};
}
class Question {
final String answer;
final String name;
final List<String> options;
final dynamic select;
Question({
this.answer,
this.name,
this.options,
this.select,
});
Question copyWith({
String answer,
String name,
List<String> options,
dynamic select,
}) =>
Question(
answer: answer ?? this.answer,
name: name ?? this.name,
options: options ?? this.options,
select: select ?? this.select,
);
factory Question.fromRawJson(String str) => Question.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Question.fromJson(Map<String, dynamic> json) => Question(
answer: json["answer"] == null ? null : json["answer"],
name: json["name"] == null ? null : json["name"],
options: json["options"] == null ? null : List<String>.from(json["options"].map((x) => x)),
select: json["select"],
);
Map<String, dynamic> toJson() => {
"answer": answer == null ? null : answer,
"name": name == null ? null : name,
"options": options == null ? null : List<dynamic>.from(options.map((x) => x)),
"select": select,
};
}