How to use model in flutter - flutter

I am storing json object in a model and trying to access properties of my model but I am not able to access my properties which is in my model following is my json object which I am storing in model
{
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 35,
"title": "Astrology",
"filename": "Astrology.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 53,
"title": "vgb",
"filename": "vgb.jpg",
"mimetype": "image/jpeg",
"directcalling": 0,
"parentid": 35,
"subcat": []
}
]
},
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
]
},
{
"id": 37,
"title": "DharamSandhehalu",
"filename": "DharamSandhehalu.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": []
},
{
"id": 38,
"title": "Allpoojas",
"filename": "Allpoojas.jpg",
"mimetype": "image/jpeg",
"directcalling": 0,
"parentid": null,
"subcat": [
{
"id": 40,
"title": "gugu",
"filename": "gugu.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 38,
"subcat": []
}
]
}
]
}
following is my model class where I am storing my json object
class Categories {
Categories({
required this.statusCode,
required this.success,
required this.messages,
required this.data,
});
late final int statusCode;
late final bool success;
late final List<dynamic> messages;
late final List<Data> data;
Categories.fromJson(Map<String, dynamic> json) {
statusCode = json['statusCode'];
success = json['success'];
messages = List.castFrom<dynamic, dynamic>(json['messages']);
data = List.from(json['data']).map((e) => Data.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['statusCode'] = statusCode;
_data['success'] = success;
_data['messages'] = messages;
_data['data'] = data.map((e) => e.toJson()).toList();
return _data;
}
}
class Data {
Data({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final Null parentid;
late final List<Subcat> subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
_data['parentid'] = parentid;
_data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
required this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int parentid;
late final List<dynamic> subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
_data['parentid'] = parentid;
_data['subcat'] = subcat;
return _data;
}
}
following is my api where I am getting response and storing in my model
Future<void> getCatogories(BuildContext cont) async {
final url = PurohitApi().baseUrl + PurohitApi().getcatogory;
try {
var response = await http.get(
Uri.parse(url),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
);
Map<String, dynamic> categoryTypes = json.decode(response.body);
if (categoryTypes['data'] != null) {
categories = categoryTypes['data'];
}
categorieModel = Categories.fromJson(categoryTypes);
print(sample!.filename);
notifyListeners();
} catch (e) {
print(e);
}
}
now I am trying to access list which is in categories class which I am not getting how to do

Try following demo
import 'package: flutter/material.dart';
import 'dart:convert';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
String jsonString = "{" +
" \"statusCode\": 200," +
" \"success\": true," +
" \"messages\": []," +
" \"data\": [" +
" {" +
" \"id\": 35," +
" \"title\": \"Astrology\"," +
" \"filename\": \"Astrology.jpg\"," +
" \"mimetype\": \"image/jpeg\"," +
" \"directcalling\": 1," +
" \"parentid\": null," +
" \"subcat\": [" +
" {" +
" \"id\": 53," +
" \"title\": \"vgb\"," +
" \"filename\": \"vgb.jpg\"," +
" \"mimetype\": \"image/jpeg\"," +
" \"directcalling\": 0," +
" \"parentid\": 35," +
" \"subcat\": []" +
" }" +
" ]" +
" }," +
" {" +
" \"id\": 36," +
" \"title\": \"Muhurtam\"," +
" \"filename\": \"Muhurtam.jpg\"," +
" \"mimetype\": \"image/jpeg\"," +
" \"directcalling\": 1," +
" \"parentid\": null," +
" \"subcat\": [" +
" {" +
" \"id\": 50," +
" \"title\": \"abc\"," +
" \"filename\": \"abc.png\"," +
" \"mimetype\": \"image/png\"," +
" \"directcalling\": 0," +
" \"parentid\": 36," +
" \"subcat\": []" +
" }" +
" ]" +
" }," +
" {" +
" \"id\": 37," +
" \"title\": \"DharamSandhehalu\"," +
" \"filename\": \"DharamSandhehalu.jpg\"," +
" \"mimetype\": \"image/jpeg\"," +
" \"directcalling\": 1," +
" \"parentid\": null," +
" \"subcat\": []" +
" }," +
" {" +
" \"id\": 38," +
" \"title\": \"Allpoojas\"," +
" \"filename\": \"Allpoojas.jpg\"," +
" \"mimetype\": \"image/jpeg\"," +
" \"directcalling\": 0," +
" \"parentid\": null," +
" \"subcat\": [" +
" {" +
" \"id\": 40," +
" \"title\": \"gugu\"," +
" \"filename\": \"gugu.png\"," +
" \"mimetype\": \"image/png\"," +
" \"directcalling\": 0," +
" \"parentid\": 38," +
" \"subcat\": []" +
" }" +
" " +
" ]" +
" }" +
" ]" +
"}";
#override
Widget build(BuildContext context) {
return
ListView.builder(
itemCount: Categories.fromJson(json.decode(jsonString)).data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: const Icon(Icons.list),
trailing: Text(
(Categories.fromJson(json.decode(jsonString)).data[index].subcat.length.toString()),
style: TextStyle(color: Colors.green, fontSize: 15),
),
title: Text((Categories.fromJson(json.decode(jsonString)).data[index].title)));
});
}
}
class Categories {
Categories({
required this.statusCode,
required this.success,
required this.messages,
required this.data,
});
late final int statusCode;
late final bool success;
late final List<dynamic> messages;
late final List<Data> data;
Categories.fromJson(Map<String, dynamic> json) {
statusCode = json['statusCode'];
success = json['success'];
messages = List.castFrom<dynamic, dynamic>(json['messages']);
data = List.from(json['data']).map((e) => Data.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['statusCode'] = statusCode;
_data['success'] = success;
_data['messages'] = messages;
_data['data'] = data.map((e) => e.toJson()).toList();
return _data;
}
}
class Data {
Data({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final Null parentid;
late final List<Subcat> subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
_data['parentid'] = parentid;
_data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
required this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int parentid;
late final List<dynamic> subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
_data['parentid'] = parentid;
_data['subcat'] = subcat;
return _data;
}
}

Related

How to set the list of json data in flutter

I'm trying to return the items from this api https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812
but always the error:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
this my object and model:
Future<ProdutoModel> getProduto() async {
try {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
_accountListModel = ProdutoModel.fromJson(res);
var data = res['filhos'] as List;
setState(() {
_list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
});
return _accountListModel;
} catch (e) {
rethrow;
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
return this api
The returned is at List, so you have to do something like:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> main() async {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
var list = res as List;
for (var item in list) {
var _accountListModel = ProdutoModel.fromJson(item); // model per item
print(_accountListModel.phone);
var data = item['filhos'] as List;
var _list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
print(_list);
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
[
{
"phone": "48984974812",
"desperson": "Usuario admin",
"desemail": "admin#hcode.com.br",
"filhos": [
{
"age": 7,
"firstname": "Lorenzo",
"lastname": "Chaves"
},
{
"age": 14,
"firstname": "teste",
"lastname": "acompanhante"
},
{
"age": 14,
"firstname": "meu",
"lastname": "filho"
},
{
"age": 21,
"firstname": "teste",
"lastname": "teste"
}
]
}
]
You have type conversion issue make sure the types from the api is the same as the model
you can use this website : https://app.quicktype.io
to generate model to any json file without get any erorr and it gets you functions from json and to json

Flutter: How to listen changes inside the list which is in model using provider?

I am trying to handle a model which has a list but I stucking in between I am not getting any idea how to handle list which is in my model first of all I am getting data from api and I am storing Jason object in my model which is working perfect following is my json model
{
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 35,
"title": "Astrology",
"filename": "Astrology.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": []
},
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
now I am Saving above json object in below model following is my model class
class Data {
Data({
this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final Null parentid;
late final List<Subcat>? subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
// _data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
// _data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
// _data['parentid'] = parentid;
// _data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int? parentid;
late final List<dynamic>? subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
//_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
//_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
//_data['parentid'] = parentid;
//_data['subcat'] = subcat;
return _data;
}
}
I am updating particular id in list:subcat which is in my Data class now I want to show changes to user after updating following is my update function
Data findById(int id) {
return categories!.data.firstWhere((cat) => cat.id == id);
}
Future<void> updateCatAtributes(
int id, BuildContext context, Subcat newCat, Data subid) async {
print('updating....${newCat.toJson()}');
final catIndex = subid.subcat!.indexWhere((prod) => prod.id == id);
if (catIndex >= 0) {
subid.subcat![catIndex] = newCat;
notifyListeners();
} else {
print('...');
}
following is my dropdown widget where I want to display changed title in my menu item
final loadedProduct = Provider.of<Category>(
context,
listen: false,
).findById(catId);
Consumer<Category>(
builder: (context, value, child) {
return Column(
children: [
DropdownButton<String>(
elevation: 16,
isExpanded: true,
hint: Text('please select sub category'),
items: loadedProduct.subcat!.map((v) {
return DropdownMenuItem<String>(
onTap: () {
subcat = v.id;
_initValues = {
'title': v.title,
};
},
value: v.title,
child: Text(v.title));
}).toList(),
onChanged: (val) {
value.updatesubcat(val!);
print(val);
},
value: value.sub,
),
],

how can i call data from a model class which in list model flutter

I am trying to get data from my model but I am not getting the data in text widget.After receiving data from JSON I am using model to save data I am able to print data after API call in function but not when I tried to get data from model inside widget.I am using provider but receiving null value from model I am not getting exactly how to achieve this task following is my JSON object
{
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
]
I had created model class for the above json below is my model
Model
import 'package:flutter/material.dart';
class Categories with ChangeNotifier {
Categories({
this.statusCode,
this.success,
this.messages,
this.data,
});
late final int? statusCode;
late final bool? success;
late final List<dynamic>? messages;
late final List<Data>? data;
Categories.fromJson(Map<String, dynamic> json) {
statusCode = json['statusCode'];
success = json['success'];
messages = List.castFrom<dynamic, dynamic>(json['messages']);
data = List.from(json['data']).map((e) => Data.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['statusCode'] = statusCode;
_data['success'] = success;
_data['messages'] = messages;
_data['data'] = data!.map((e) => e.toJson()).toList();
return _data;
}
List get items {
// if (_showFavoritesOnly) {
// return _items.where((prodItem) => prodItem.isFavorite).toList();
// }
return [...data!];
}
}
class Data extends ChangeNotifier {
Data({
this.id,
this.title,
this.filename,
this.mimetype,
this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String? title;
late final String? filename;
late final String? mimetype;
late final int? directcalling;
late final Null parentid;
late final List<Subcat>? subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
// _data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
// _data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
// _data['parentid'] = parentid;
// _data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
required this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
required this.parentid,
required this.subcat,
});
late final int id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int parentid;
late final List<dynamic> subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
//_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
//_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
//_data['parentid'] = parentid;
//_data['subcat'] = subcat;
return _data;
}
}
following is my widget where I want to check data inside my model.i am not getting exactly how to call data which is inside model
Widget build(BuildContext context) {
var image = Provider.of<FlutterFunctions>(context, listen: false);
var cat = Provider.of<Category>(context, listen: false).categories;
return Scaffold(
appBar: AppBar(),
drawer: const AppDrawer(),
body: Text("${cat?.data == null ? "there is no data" : cat!.statusCode}")
Api Conversion
class Category with ChangeNotifier {
Categories? categories;
Future<void> getCatogories(BuildContext cont) async {
final url = PurohitApi().baseUrl + PurohitApi().getcategory;
try {
final client = RetryClient(
http.Client(),
retries: 4,
when: (response) {
return response.statusCode == 401 ? true : false;
},
onRetry: (req, res, retryCount) async {
//print('retry started $token');
if (retryCount == 0 && res?.statusCode == 401) {
var accessToken = await Provider.of<Auth>(cont, listen: false)
.restoreAccessToken();
// Only this block can run (once) until done
req.headers['Authorization'] = accessToken;
}
},
);
var response = await client.get(
Uri.parse(url),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
);
Map<String, dynamic> categoryTypes = json.decode(response.body);
categories = Categories.fromJson(categoryTypes);
notifyListeners();
} catch (e) {
print(e);
}
}
}
You are using Provider the wrong way. Your models such as Categories,Data etc. should not extend ChangeNotifier. You have to make Provider class which uses ChangeNotifier which will have your model data and provide it somewhere to use it with Provider.of<ProviderName>(context, listen: false). Something like this:
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => CategoriesProvider(),
child: MaterialApp(
home: Sample(),
),
);
}
}
class CategoriesProvider with ChangeNotifier {
Categories? categories;
Future<void> getCatogories() async {
Map<String, dynamic> categoryTypes = {
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
]
}
]
};
categories = Categories.fromJson(categoryTypes);
notifyListeners();
}
}
class Sample extends StatefulWidget {
const Sample({Key? key}) : super(key: key);
#override
State<Sample> createState() => _SampleState();
}
class _SampleState extends State<Sample> {
#override
void initState() {
Provider.of<CategoriesProvider>(context, listen: false).getCatogories();
super.initState();
}
#override
Widget build(BuildContext context) {
var cat = Provider.of<CategoriesProvider>(context, listen: false).categories;
return Scaffold(
appBar: AppBar(),
drawer: const Drawer(),
body: Text("${cat?.data == null ? "there is no data" : cat!.statusCode}"),
);
}
}

Store JSON to a Map

I have a JSON response that I would like to store in a map but do not seem to understand how to proceed with this. The JSON that I would like to store is:
{
"results": [
{
"gender": "female",
"name": {
"title": "Mrs",
"first": "Claudine",
"last": "da Mota"
},
"location": {
"street": {
"number": 4066,
"name": "Beco dos Namorados"
},
"city": "Poá",
"state": "Amapá",
"country": "Brazil",
"postcode": 55840,
"coordinates": {
"latitude": "-72.3427",
"longitude": "112.5891"
},
"timezone": {
"offset": "-8:00",
"description": "Pacific Time (US & Canada)"
}
},
"email": "claudine.damota#example.com",
"login": {
"uuid": "247261b1-80a5-428a-a906-a381efe93cb7",
"username": "happyostrich285",
"password": "2000",
"salt": "bQwiFMAM",
"md5": "c60b9d4138e4fb0d76182d3397ab35bd",
"sha1": "d8e40944ed0d9d95f6c44d3d40f9d9e26e3cc04a",
"sha256": "71d28bb93f2a386c23591c091c3b2bab2e1af89c3ad6d83af359398eb0637fe3"
},
"dob": {
"date": "1974-08-05T08:07:07.202Z",
"age": 47
},
"registered": {
"date": "2003-11-08T05:19:12.790Z",
"age": 18
},
"phone": "(98) 5277-4740",
"cell": "(53) 0832-4652",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/89.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/89.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/89.jpg"
},
"nat": "BR"
},
{
"gender": "male",
"name": {
"title": "Mr",
"first": "Lauri",
"last": "Autio"
},
"location": {
"street": {
"number": 7571,
"name": "Tahmelantie"
},
"city": "Pälkäne",
"state": "Lapland",
"country": "Finland",
"postcode": 58979,
"coordinates": {
"latitude": "40.0496",
"longitude": "-34.1528"
},
"timezone": {
"offset": "-12:00",
"description": "Eniwetok, Kwajalein"
}
},
"email": "lauri.autio#example.com",
"login": {
"uuid": "1850e546-a847-4770-8cdb-48903c2874d1",
"username": "beautifulleopard611",
"password": "stinger",
"salt": "LcnXkFBq",
"md5": "0945ff84c37005726194b3f3c81bbb39",
"sha1": "87945a6d1feae97e03cf92b166b0063b85328175",
"sha256": "382f38e3f0105f0ddac0de9c10043f0928e471196d9e16204b4e2db0e00da62c"
},
"dob": {
"date": "1958-06-04T08:53:39.167Z",
"age": 63
},
"registered": {
"date": "2008-04-08T08:12:25.490Z",
"age": 13
},
"phone": "09-874-759",
"cell": "041-737-00-52",
"id": {
"name": "HETU",
"value": "NaNNA101undefined"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/75.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/75.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg"
},
"nat": "FI"
},
]
}
This is the approach I have taken but it doesn't seem to work:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:core';
class Profile {
final String userName;
final String name;
final String emailId;
final int timePeriod;
final int age;
final String nationality;
final String number;
final int streetNumber;
final String streetName;
final String city;
final String country;
final int postCode;
final String picture;
Profile({
required this.userName,
required this.name,
required this.emailId,
required this.timePeriod,
required this.age,
required this.nationality,
required this.number,
required this.streetNumber,
required this.streetName,
required this.city,
required this.country,
required this.postCode,
required this.picture
});
}
class ProfileProvider with ChangeNotifier {
Map<String, Profile> _data = {};
Map<String, Profile> get data {
return {..._data};
}
Future<void> fetchData() async {
final url = Uri.parse('https://randomuser.me/api/?results=50');
final response = await http.get(url);
final extractedData = json.decode(response.body);
print(extractedData);
Map<String, Profile> map = {};
extractedData.forEach((key, value) => //51:19
map.putIfAbsent(key, () => //52:13
Profile(
userName: value['login']['username'], //54:32
name: value['name']['first'],
emailId: value['email'],
timePeriod: value['registered']['age'],
age: value['dob']['age'],
nationality: value['nat'],
number: value['cell'],
streetNumber: value['location']['street']['number'],
streetName: value['location']['street']['name'],
city: value['location']['city'],
country: value['location']['country'],
postCode: value['location']['postcode'],
picture: value['picture']['large']
)
)
);
_data = map;
notifyListeners();
}
}
The way I see it, the problem lies from 54:32 onwards and I now have no idea how to get past it to get the code to work. I find this approach easy to understand so ideally would prefer the answers to be in the same but other approaches are welcome.
This is the error I get. The line numbers with the errors are marked in the code:
E/flutter (20478): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (20478): #0 ProfileProvider.fetchData.<anonymous closure>.<anonymous closure> (package:profile_app/provider/data.dart:54:32)
E/flutter (20478): #1 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:311:23)
E/flutter (20478): #2 ProfileProvider.fetchData.<anonymous closure> (package:profile_app/provider/data.dart:52:13)
E/flutter (20478): #3 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (20478): #4 ProfileProvider.fetchData (package:profile_app/provider/data.dart:51:19)
E/flutter (20478): <asynchronous suspension>
E/flutter (20478):
the data type of "number" is int but you've added String.
I'd recommend to manage Models in a separately. also for the beginning use json to dart and then use that class name to decode or encode the json response.
Profile profile = Profile.Fromjson(json.decode('String'));
Try out below Model Class
class ProfileModel {
ProfileModel({
required this.results,
required this.info,
});
late final List<Results> results;
late final Info info;
ProfileModel.fromJson(Map<String, dynamic> json){
results = List.from(json['results']).map((e)=>Results.fromJson(e)).toList();
info = Info.fromJson(json['info']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['results'] = results.map((e)=>e.toJson()).toList();
_data['info'] = info.toJson();
return _data;
}
}
class Results {
Results({
required this.gender,
required this.name,
required this.location,
required this.email,
required this.login,
required this.dob,
required this.registered,
required this.phone,
required this.cell,
required this.id,
required this.picture,
required this.nat,
});
late final String gender;
late final Name name;
late final Location location;
late final String email;
late final Login login;
late final Dob dob;
late final Registered registered;
late final String phone;
late final String cell;
late final Id id;
late final Picture picture;
late final String nat;
Results.fromJson(Map<String, dynamic> json){
gender = json['gender'];
name = Name.fromJson(json['name']);
location = Location.fromJson(json['location']);
email = json['email'];
login = Login.fromJson(json['login']);
dob = Dob.fromJson(json['dob']);
registered = Registered.fromJson(json['registered']);
phone = json['phone'];
cell = json['cell'];
id = Id.fromJson(json['id']);
picture = Picture.fromJson(json['picture']);
nat = json['nat'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['gender'] = gender;
_data['name'] = name.toJson();
_data['location'] = location.toJson();
_data['email'] = email;
_data['login'] = login.toJson();
_data['dob'] = dob.toJson();
_data['registered'] = registered.toJson();
_data['phone'] = phone;
_data['cell'] = cell;
_data['id'] = id.toJson();
_data['picture'] = picture.toJson();
_data['nat'] = nat;
return _data;
}
}
class Name {
Name({
required this.title,
required this.first,
required this.last,
});
late final String title;
late final String first;
late final String last;
Name.fromJson(Map<String, dynamic> json){
title = json['title'];
first = json['first'];
last = json['last'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['title'] = title;
_data['first'] = first;
_data['last'] = last;
return _data;
}
}
class Location {
Location({
required this.street,
required this.city,
required this.state,
required this.country,
required this.postcode,
required this.coordinates,
required this.timezone,
});
late final Street street;
late final String city;
late final String state;
late final String country;
late final int? postcode;
late final Coordinates coordinates;
late final Timezone timezone;
Location.fromJson(Map<String, dynamic> json){
street = Street.fromJson(json['street']);
city = json['city'];
state = json['state'];
country = json['country'];
postcode = json['postcode'];
coordinates = Coordinates.fromJson(json['coordinates']);
timezone = Timezone.fromJson(json['timezone']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['street'] = street.toJson();
_data['city'] = city;
_data['state'] = state;
_data['country'] = country;
_data['postcode'] = postcode;
_data['coordinates'] = coordinates.toJson();
_data['timezone'] = timezone.toJson();
return _data;
}
}
class Street {
Street({
required this.number,
required this.name,
});
late final int number;
late final String name;
Street.fromJson(Map<String, dynamic> json){
number = json['number'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['number'] = number;
_data['name'] = name;
return _data;
}
}
class Coordinates {
Coordinates({
required this.latitude,
required this.longitude,
});
late final String latitude;
late final String longitude;
Coordinates.fromJson(Map<String, dynamic> json){
latitude = json['latitude'];
longitude = json['longitude'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['latitude'] = latitude;
_data['longitude'] = longitude;
return _data;
}
}
class Timezone {
Timezone({
required this.offset,
required this.description,
});
late final String offset;
late final String description;
Timezone.fromJson(Map<String, dynamic> json){
offset = json['offset'];
description = json['description'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['offset'] = offset;
_data['description'] = description;
return _data;
}
}
class Login {
Login({
required this.uuid,
required this.username,
required this.password,
required this.salt,
required this.md5,
required this.sha1,
required this.sha256,
});
late final String uuid;
late final String username;
late final String password;
late final String salt;
late final String md5;
late final String sha1;
late final String sha256;
Login.fromJson(Map<String, dynamic> json){
uuid = json['uuid'];
username = json['username'];
password = json['password'];
salt = json['salt'];
md5 = json['md5'];
sha1 = json['sha1'];
sha256 = json['sha256'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['uuid'] = uuid;
_data['username'] = username;
_data['password'] = password;
_data['salt'] = salt;
_data['md5'] = md5;
_data['sha1'] = sha1;
_data['sha256'] = sha256;
return _data;
}
}
class Dob {
Dob({
required this.date,
required this.age,
});
late final String date;
late final int age;
Dob.fromJson(Map<String, dynamic> json){
date = json['date'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['date'] = date;
_data['age'] = age;
return _data;
}
}
class Registered {
Registered({
required this.date,
required this.age,
});
late final String date;
late final int age;
Registered.fromJson(Map<String, dynamic> json){
date = json['date'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['date'] = date;
_data['age'] = age;
return _data;
}
}
class Id {
Id({
required this.name,
this.value,
});
late final String name;
late final String? value;
Id.fromJson(Map<String, dynamic> json){
name = json['name'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['name'] = name;
_data['value'] = value;
return _data;
}
}
class Picture {
Picture({
required this.large,
required this.medium,
required this.thumbnail,
});
late final String large;
late final String medium;
late final String thumbnail;
Picture.fromJson(Map<String, dynamic> json){
large = json['large'];
medium = json['medium'];
thumbnail = json['thumbnail'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['large'] = large;
_data['medium'] = medium;
_data['thumbnail'] = thumbnail;
return _data;
}
}
class Info {
Info({
required this.seed,
required this.results,
required this.page,
required this.version,
});
late final String seed;
late final int results;
late final int page;
late final String version;
Info.fromJson(Map<String, dynamic> json){
seed = json['seed'];
results = json['results'];
page = json['page'];
version = json['version'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['seed'] = seed;
_data['results'] = results;
_data['page'] = page;
_data['version'] = version;
return _data;
}
}

JSON Loop flutter

I have trouble getting data from a complex json, below is the json in the request.i would like to display all comments under publication object
{
"code": 0,
"message": {
"message": "Détails de publication"
},
"publication": [
{
"id": 47,
"user_id": 4,
"name": "spadrilles",
"description": "deux spadrille presque neufs",
"category": "Bijoux",
"quantity": 0,
"size": "XS 32",
"brand": "ZARA",
"for_who": "homme",
"color": "Blanc",
"delivery": "disponible le 25-01-2020",
"price": "150.5",
"progression": 0,
"discount": "5",
"visibility": 0,
"status": "Presque Neuf",
"softdelete": 0,
"created_at": "2021-01-06T14:51:27.000000Z",
"updated_at": "2021-01-22T10:26:39.000000Z",
"picture1": "b7c992f0ac7b0edd7e7e5ee12e617d9c07411b4d343f64f1caf94aa08d08b8fc.jpg",
"picture2": "efdffb16f47e0ab40788b760ab9154fc95a1fded8f6963b227aceaff302e8623.png",
"picture3": "8e23d6ec620353c8802bb969836b5d80f6c871fdc419f695a7c1da0e71e378ff.png",
"picture4": null,
"picture5": "5f3eac05c317d25cd0d691d545236fb0ef6059870217ea50dfd45b914d997d82.png",
"comment": [
{
"id": 3,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:32.000000Z",
"updated_at": "2021-03-25T09:40:32.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
},
{
"id": 4,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:36.000000Z",
"updated_at": "2021-03-25T09:40:36.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
},
{
"id": 5,
"pub_id": 47,
"user_id": 21,
"comment": "test test testsssssssssssst",
"created_at": "2021-03-25T09:40:37.000000Z",
"updated_at": "2021-03-25T09:40:37.000000Z",
"username": "occasion_saly",
"user_picture": "1611217814.png"
}
],
"ownerpicture": "1608970983.png"
}
],
"error": {},
"status": 200
}
As you can see, under publication there are comment object and under those they have 3 comments.i want to display it all using for loop .
Kindly assist.
my code (usually dislay one comment):
#override
void initState() {
getproduct(widget.idproduct);
super.initState();
}
Future<dynamic> getproduct(int id) async {
var response = await Network().getData('/publication/show/$id');
data = json.decode(response.body)['publication'];
inspect(data);
return data;
}
child: SingleChildScrollView(
child: FutureBuilder(
future: getproduct(widget.idproduct),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
for (int i = 0; i < snapshot.data.length; i++)
CommentsList(
comment: snapshot.data[i]['comment'][i]
['comment'],
username: snapshot.data[i]['comment'][i]
['username'],
user_picture:
"${snapshot.data[i]['comment'][i]['user_picture']}",
)
],
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
Convert json to Your Entity and use it
You can use this site for Json to Dart code
Here code to convert json to Model
Response response=await http.get(url);
return YourDataEntity.fromJson(jsonDecode(resposne.body));
Here your entity
class YourDataEntity {
int code;
Message message;
List<Publication> publication;
Error error;
int status;
YourDataEntity({this.code, this.message, this.publication, this.error, this.status});
YourDataEntity.fromJson(Map<String, dynamic> json) {
code = json['code'];
message = json['message'] != null ? new Message.fromJson(json['message']) : null;
if (json['publication'] != null) {
publication = new List<Publication>();
json['publication'].forEach((v) { publication.add(new Publication.fromJson(v)); });
}
error = json['error'] != null ? new Error.fromJson(json['error']) : null;
status = json['status'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
if (this.message != null) {
data['message'] = this.message.toJson();
}
if (this.publication != null) {
data['publication'] = this.publication.map((v) => v.toJson()).toList();
}
if (this.error != null) {
data['error'] = this.error.toJson();
}
data['status'] = this.status;
return data;
}
}
class Message {
String message;
Message({this.message});
Message.fromJson(Map<String, dynamic> json) {
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['message'] = this.message;
return data;
}
}
class Publication {
int id;
int userId;
String name;
String description;
String category;
int quantity;
String size;
String brand;
String forWho;
String color;
String delivery;
String price;
int progression;
String discount;
int visibility;
String status;
int softdelete;
String createdAt;
String updatedAt;
String picture1;
String picture2;
String picture3;
Null picture4;
String picture5;
List<Comment> comment;
String ownerpicture;
Publication({this.id, this.userId, this.name, this.description, this.category, this.quantity, this.size, this.brand, this.forWho, this.color, this.delivery, this.price, this.progression, this.discount, this.visibility, this.status, this.softdelete, this.createdAt, this.updatedAt, this.picture1, this.picture2, this.picture3, this.picture4, this.picture5, this.comment, this.ownerpicture});
Publication.fromJson(Map<String, dynamic> json) {
id = json['id'];
userId = json['user_id'];
name = json['name'];
description = json['description'];
category = json['category'];
quantity = json['quantity'];
size = json['size'];
brand = json['brand'];
forWho = json['for_who'];
color = json['color'];
delivery = json['delivery'];
price = json['price'];
progression = json['progression'];
discount = json['discount'];
visibility = json['visibility'];
status = json['status'];
softdelete = json['softdelete'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
picture1 = json['picture1'];
picture2 = json['picture2'];
picture3 = json['picture3'];
picture4 = json['picture4'];
picture5 = json['picture5'];
if (json['comment'] != null) {
comment = new List<Comment>();
json['comment'].forEach((v) { comment.add(new Comment.fromJson(v)); });
}
ownerpicture = json['ownerpicture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['user_id'] = this.userId;
data['name'] = this.name;
data['description'] = this.description;
data['category'] = this.category;
data['quantity'] = this.quantity;
data['size'] = this.size;
data['brand'] = this.brand;
data['for_who'] = this.forWho;
data['color'] = this.color;
data['delivery'] = this.delivery;
data['price'] = this.price;
data['progression'] = this.progression;
data['discount'] = this.discount;
data['visibility'] = this.visibility;
data['status'] = this.status;
data['softdelete'] = this.softdelete;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
data['picture1'] = this.picture1;
data['picture2'] = this.picture2;
data['picture3'] = this.picture3;
data['picture4'] = this.picture4;
data['picture5'] = this.picture5;
if (this.comment != null) {
data['comment'] = this.comment.map((v) => v.toJson()).toList();
}
data['ownerpicture'] = this.ownerpicture;
return data;
}
}
class Comment {
int id;
int pubId;
int userId;
String comment;
String createdAt;
String updatedAt;
String username;
String userPicture;
Comment({this.id, this.pubId, this.userId, this.comment, this.createdAt, this.updatedAt, this.username, this.userPicture});
Comment.fromJson(Map<String, dynamic> json) {
id = json['id'];
pubId = json['pub_id'];
userId = json['user_id'];
comment = json['comment'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
username = json['username'];
userPicture = json['user_picture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['pub_id'] = this.pubId;
data['user_id'] = this.userId;
data['comment'] = this.comment;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
data['username'] = this.username;
data['user_picture'] = this.userPicture;
return data;
}
}
class Error {
Error();
// The response for error field is unclear
}