Not getting required value from json list - flutter - json

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

Related

Parsing Nested JSON leads to fromJson methods having a "The class 'Data' doesn't have an unnamed constructor." error

So I am trying to parse a Nested JSON from a GET request from VirusTotal but when I create the methods to parse the JSON for what I am looking for it is giving me an error on the factory methods immediately following the =>. I used the tool https://app.quicktype.io/ to get this method but it still does not seem to work. The JSON I am looking to parse looks like this and the code is below that.
{
"data": {
"attributes": {
"last_analysis_stats": {
"harmless": 81,
"malicious": 2,
"suspicious": 0
}
}
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sms/sms.dart';
import 'package:http/http.dart' as http;
Future<void> main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key:key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: "Gone Smishin'",
home: GoneSmishin(),
);
}
}
class GoneSmishin extends StatefulWidget {
const GoneSmishin({Key? key}) : super(key: key);
State<GoneSmishin> createState() {
return _GoneSmishinState();
}
}
class Data {
late Attributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data( // this is where the error appears in every method
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"attributes": attributes.toJson(),
};
}
class Attributes {
late LastAnalysisStats lastAnalysisStats;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
lastAnalysisStats: LastAnalysisStats.fromJson(json["last_analysis_stats"]),
);
Map<String, dynamic> toJson() => {
"last_analysis_stats": lastAnalysisStats.toJson(),
};
}
class LastAnalysisStats {
static late int harmless;
static late int malicious;
static late int suspicious;
factory LastAnalysisStats.fromJson(Map<String, dynamic> json) => LastAnalysisStats(
harmless: json["harmless"],
malicious: json["malicious"],
suspicious: json["suspicious"],
);
Map<String, dynamic> toJson() => {
//"harmless": harmless,
"malicious": malicious,
"suspicious": suspicious,
};
}
class _GoneSmishinState extends State<GoneSmishin> {
late Data data;
String message = "";
String word = "";
bool isOn = false;
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
var queryStatus = '';
var urlStatus = '';
var attributes = '';
String urlHaus = "URLHaus";
String virusTotal = "VirusTotal";
String list = "Whitelist";
urlHausParseBox() async {
String url = myController.text;
var urlEncoded = base64.encode(utf8.encode(myController.text));
var urlNoPadding = urlEncoded.replaceAll(new RegExp(r'='), '');
// await VirusTotal().getUrlAnalysisReport(urlNoPadding);
final response2 = await http.get(
Uri.parse("https://www.virustotal.com/api/v3/urls/$urlNoPadding"),
headers: <String, String>{
'Accept': 'application/json',
'x-apikey': '111111111111111111111'
},
);
print(urlEncoded);
print(response2.body);
if (response2.statusCode == 200) {
setState(() {
final decoded = json.decode(response2.body);
data = decoded['data'];
});
}
if (queryStatus == "ok" && urlStatus == "online") {
print("found");
setState(() {
urlHaus = 'Found in URLHause Database - Probably Smishing';
});
} else if (queryStatus == "ok" && urlStatus == "offline") {
print("found offline");
setState(() {
urlHaus = 'Found in URLHaus, not online';
});
} else {
print("not found");
setState(() {
urlHaus = 'Found Nothing';
});
}
if (((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious)) >= 2) {
setState(() {
virusTotal = 'Found in VirusTotal - Possibly Malicious';
});
} else
if (((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious)) <= 1) {
setState(() {
virusTotal = 'Found in VirusTotal - Probably not Malicious';
print((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious));
});
} else {
setState(() {
virusTotal = 'Not found in VirusTotal';
});
}
Can you try to use the json model like this?
import 'dart:convert';
Model modelFromJson(String str) => Model.fromJson(json.decode(str));
String modelToJson(Model data) => json.encode(data.toJson());
class Model {
Model({
this.data,
});
Data data;
factory Model.fromJson(Map<String, dynamic> json) => Model(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
this.attributes,
});
Attributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data(
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"attributes": attributes.toJson(),
};
}
class Attributes {
Attributes({
this.lastAnalysisStats,
});
LastAnalysisStats lastAnalysisStats;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
lastAnalysisStats: LastAnalysisStats.fromJson(json["last_analysis_stats"]),
);
Map<String, dynamic> toJson() => {
"last_analysis_stats": lastAnalysisStats.toJson(),
};
}
class LastAnalysisStats {
LastAnalysisStats({
this.harmless,
this.malicious,
this.suspicious,
});
int harmless;
int malicious;
int suspicious;
factory LastAnalysisStats.fromJson(Map<String, dynamic> json) => LastAnalysisStats(
harmless: json["harmless"],
malicious: json["malicious"],
suspicious: json["suspicious"],
);
Map<String, dynamic> toJson() => {
"harmless": harmless,
"malicious": malicious,
"suspicious": suspicious,
};
}

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.

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'SubJsonModel' - flutter

Am trying to get a data from a json url but i get the error
Unhandled Exception: type 'List' is not a subtype of type 'SubJsonModel'
main.dart
final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() 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) {
myModel.add(JsonModel(data['cat_id'], data['category'], data['cat_subcategory']));
setState(() {});
}
print(myModel[1].subCat.name);
}else {
print("Something went wrong!");
}
}
model.dart
class JsonModel {
final String id;
final String category;
SubJsonModel subCat;
JsonModel(this.id, this.category, this.subCat);
}
class SubJsonModel {
final String name;
final String image;
SubJsonModel(this.name, this.image);
}
please how do i solve this
So here what I do first create a model class with the help of this online tool. And then changed code like first save subcategory in one list and then passed it to the main list and then print
Here is my loadData() method
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List myModel = [];
loadData() 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) {
List<CatSubcategory> subCate = []; // Set a emoty list of CatSubcategory
data['cat_subcategory'].map((x) { // Here parsed the cat_subcategory data and simply add it into list
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList(); // and this done for we get map data so convert this data toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
print(myModel[0].catSubcategory[0].subName);
} else {
print("Something went wrong!");
}
}
here is my model class
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,
};
}
You can use https://app.quicktype.io/ to create the model.dart from a json.
To parse this JSON data, do
final pieSingleChartInfo = pieSingleChartInfoFromJson(jsonString);
import 'dart:convert';
List<PieSingleChartInfo> pieSingleChartInfoFromJson(String str) => List<PieSingleChartInfo>.from(json.decode(str).map((x) => PieSingleChartInfo.fromJson(x)));
String pieSingleChartInfoToJson(List<PieSingleChartInfo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class PieSingleChartInfo {
PieSingleChartInfo({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory PieSingleChartInfo.fromJson(Map<String, dynamic> json) => PieSingleChartInfo(
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,
};
}
I noted a few issues and corrected them based on the information you provided.
Read the comments. Add a sample response body to the question.
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() 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) {
// first create SubJsonModel object
var subCat = SubJsonModel(
data['cat_subcategory']['name'], data['cat_subcategory']['image']);
//use subCat to create JsonModel
myModel.add(JsonModel(data['cat_id'], data['category'], subCat));
setState(() {});
}
print(myModel[1].subCat.name);
} else {
print("Something went wrong!");
}
}

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;
}
}