How to Print instance in Flutter/Dart? [duplicate] - json

This question already has answers here:
Default stringify for objects, equivalent to Java's toString?
(3 answers)
Closed 1 year ago.
I have one data type Map<String,CartItem> _items = {};
And using print(_items)
And the output is:
{
p1: Instance of 'CartItem',
p2: Instance of 'CartItem'
}
Is there any method by which I can see the full logs(values) of CartItem? as my expectation is:
{
p1: some json formatted structure,
p2: some json formatted structure
}
class CartItem {
final String id;
final String title;
CartItem({
#required this.id,
#required this.title,
});
}

You just need to override your toString method:
class CartItem {
final String id;
final String title;
CartItem({
required this.id,
required this.title,
});
#override
String toString() {
return '{id: $id, title: $title}';
}
}
Usage:
main() async {
CartItem item = CartItem(id: '1', title: 'title');
print(item); // {id: 1, title: title}
Map<String, CartItem> items = {
'p1': CartItem(id: '1', title: 'title'),
'p2': CartItem(id: '2', title: 'titl2'),
};
print(items); // {p1: {id: 1, title: title}, p2: {id: 2, title: titl2}}
List<CartItem> list = [
CartItem(id: '1', title: 'title'),
CartItem(id: '2', title: 'title2'),
];
print(list); // [{id: 1, title: title}, {id: 2, title: title2}]
}

You have to loop through the items to get their specific values and not their instances.
_items.forEach((item) {
print('id: ${item.id}, title: ${item.title}');
});

Related

How to convert the below response to String?

Here is my List of maps. But I want to convert these to string.
[{tid: 20210813, title: hello3, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549e}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549d}, {tid: 20210814, title: hello4, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549f}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ecc3f047ff077fe8d454a0}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ece09647ff077fe8d454e6}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ece09647ff077fe8d454e9}, {tid: 20210813, title: 2766767236, description: hello good evening every one, _id: 62ece09647ff077fe8d454e7}, {tid: 20210814, title: hello4, description: hello good evening every one, _id: 62ece09647ff077fe8d454e8}]
You can use this model class
import 'dart:convert';
class ModelClass {
final int? tid;
final String? title;
final String? description;
final String? sId;
ModelClass({
this.tid,
this.title,
this.description,
this.sId,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (tid != null) {
result.addAll({'tid': tid});
}
if (title != null) {
result.addAll({'title': title});
}
if (description != null) {
result.addAll({'description': description});
}
if (sId != null) {
result.addAll({'sId': sId});
}
return result;
}
factory ModelClass.fromMap(Map<String, dynamic> map) {
return ModelClass(
tid: map['tid']?.toInt(),
title: map['title'],
description: map['description'],
sId: map['sId'],
);
}
String toJson() => json.encode(toMap());
factory ModelClass.fromJson(String source) =>
ModelClass.fromMap(json.decode(source));
}
And to get items
final data = jsonDecode(response.body) as List;
return data.map((e) => ModelClass.fromMap(e)).toList();
You need to decode the response into json before getting values
getAllTodos(BuildContext context) async {
try {
var todos = await _homeRepo.getAllTodos(context);
return todoFromJson(jsonDecode(todos));
}
catch (e) {
Fluttertoast.showToast(msg: e.toString()); return null;
}
}
You didn't phrase your question very clearly, but here's some speculation.
First, the map itself has the wrong structure. This is what the correct one looks like:
List myList = [
{
'tid': 20210813,
'title': 'hello3',
'description': 'hello good evening every one',
'_id': '62ecc3f047ff077fe8d4549e'
},
{}
];
You can convert everything to a string with a simple command toString(). Do a for and call toString().
main() {
String str = myList.toString(); // or all
for (final m in myList ){
m.toString();
}
}
However, I assume that in your case you need to convert the maps into a model class by presenting a toJson()/fromJson() or toString()/fromString() method for conversions.

how can i fetch nested json data

#I am able to fetch id name address but i am not able to fetch image which is src which is inside image need help
#This is my model class
class CategoryModel with ChangeNotifier{
CategoryModel({
this.id,
this.name,
this.slug,
this.parent,
this.description,
this.display,
this.image,
this.menuOrder,
this.count,
this.yoastHead,
this.yoastHeadJson,
this.links,
});
int? id;
String? name;
String? slug;
int? parent;
String? description;
String? display;
Image? image;
int? menuOrder;
int? count;
String? yoastHead;
YoastHeadJson? yoastHeadJson;
Links? links;
factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
id: json["id"],
name: json["name"],
slug: json["slug"],
parent: json["parent"],
description: json["description"],
display: json["display"],
image: json["image"] == null ? null : Image.fromJson(json["image"]),
menuOrder: json["menu_order"],
count: json["count"],
yoastHead: json["yoast_head"],
yoastHeadJson: YoastHeadJson.fromJson(json["yoast_head_json"]),
links: Links.fromJson(json["_links"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"slug": slug,
"parent": parent,
"description": description,
"display": display,
"image": image == null ? null : image!.toJson(),
"menu_order": menuOrder,
"count": count,
"yoast_head": yoastHead,
"yoast_head_json": yoastHeadJson!.toJson(),
"_links": links!.toJson(),
};
}
class Image {
Image({
this.id,
this.dateCreated,
this.dateCreatedGmt,
this.dateModified,
this.dateModifiedGmt,
this.src,
this.name,
this.alt,
});
int? id;
DateTime? dateCreated;
DateTime? dateCreatedGmt;
DateTime? dateModified;
DateTime? dateModifiedGmt;
String? src;
String? name;
String? alt;
factory Image.fromJson(Map<String, dynamic> json) => Image(
id: json["id"],
dateCreated: DateTime.parse(json["date_created"]),
dateCreatedGmt: DateTime.parse(json["date_created_gmt"]),
dateModified: DateTime.parse(json["date_modified"]),
dateModifiedGmt: DateTime.parse(json["date_modified_gmt"]),
src: json["src"],
name: json["name"],
alt: json["alt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"date_created": dateCreated!.toIso8601String(),
"date_created_gmt": dateCreatedGmt!.toIso8601String(),
"date_modified": dateModified!.toIso8601String(),
"date_modified_gmt": dateModifiedGmt!.toIso8601String(),
"src": src,
"name": name,
"alt": alt,
};
}
#This is how i try to fetch data. i am trying to fetch data and store that data in a list so that i can render that data according to my design
Future<void> fetchCategory(BuildContext context) async{
const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
try{
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
print(extractedData);
List<CategoryModel> loadedData = [];
if(extractedData == null){
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Data is Null failed to fetch data!"),
duration: Duration(seconds: 3),));
}
extractedData.forEach((element){
loadedData.add(CategoryModel(
id:element['id'],
name:element['name'],
image: element['image']['src']
// image: element!['image']
// image: element['image']==null?Text("no Image to show"):element['image']['src']
));
});
_cItems = loadedData;
print(_cItems);
notifyListeners();
}catch(e){
rethrow;
}
}
#But i am unable to fetch image Image is in nested data like this
[
{id: 25,
name: Bakery,
slug: bakery,
parent: 0,
description: ,
display: products,
image: {
id: 83,
date_created: 2021-07-16T12:16:24,
date_created_gmt: 2021-07-16T12:16:24,
date_modified: 2021-07-16T12:16:24,
date_modified_gmt: 2021-07-16T12:16:24,
src: https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-content/uploads/2021/07/Intersection.png,
name: Intersection,
alt:
}
]
#I wanna fetch the src inside Image
Shouldn't you use the fromJson method that you have declared in the CategoryModel?
*edit
Something like this:
loadedData.add(CategoryModel.fromJson(element));
**edit
How to filter data?
Future<void> fetchCategory(BuildContext context) async{
const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
try{
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
print(extractedData);
List<CategoryModel> loadedData = [];
if(extractedData == null){
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Data is Null failed to fetch data!"),
duration: Duration(seconds: 3),));
}
extractedData.forEach((element){
// Something like this to filter the elements before adding to list.
final item = CategoryModel.fromJson(element);
if(item.on_sale == true){
loadedData.add(CategoryModel.fromJson(element));
}
});
_cItems = loadedData;
print(_cItems);
notifyListeners();
}catch(e){
rethrow;
}
}
Use https://app.quicktype.io/ to easily create model classes to parse from and to json.
And yes, it is available to dart and so many other languages.

flutter application that populates a dropdown menu from json

I am a newbie in flutter and I'm trying to create 3 dropdown menus from a json file hosted online. Here is a sample of the json file. This is the link to the json file and this is the model class:
class DropdownModel {
DropdownModel({
this.sports,
this.movies,
this.tv,
});
List<Movie> sports;
List<Movie> movies;
List<Movie> tv;
factory DropdownModel.fromJson(Map<String, dynamic> json) => DropdownModel(
sports: List<Movie>.from(json["sports"].map((x) => Movie.fromJson(x))),
movies: List<Movie>.from(json["movies"].map((x) => Movie.fromJson(x))),
tv: List<Movie>.from(json["tv"].map((x) => Movie.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sports": List<dynamic>.from(sports.map((x) => x.toJson())),
"movies": List<dynamic>.from(movies.map((x) => x.toJson())),
"tv": List<dynamic>.from(tv.map((x) => x.toJson())),
};
}
class Movie {
Movie({
this.id,
this.name,
});
int id;
String name;
factory Movie.fromJson(Map<String, dynamic> json) => Movie(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
How do I go about it?
EDIT
After searching around got a solution I came across this solution which answers my question
An example would be:
// Let's supose you have a variable of the DropdownModel
DropwdownModel model = DropdownModel(...);
// We store the current dropdown value
// Here you can put the default option
// Since you have Movies with id, I would recommend saving
// the movie value as the dropdownValue
String dropdownValue = '';
// For example, let's use the music
#override
Widget build(BuildContext context) {
// We define the dropdown button
return DropdownButton<String>(
// The value is the selected value, you should control the state
value: model.fromNameFromId(dropdownValue),
// The icon to open the dropdown
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
// On changed is the method that it is called when a dropdown option
// is selected
onChanged: (String? newValue) {
// Here we change the state, as I noted before
// The newValue will be a movie id
setState(() {
dropdownValue = newValue!;
});
},
items: model.movies.map<DropdownMenuItem<String>>(
// We have to iterate through all the movies and return
// a list of DropdownMenuItems
(Movie m) {
return DropdownMenuItem<String>(
value: m.id,
// We display the movie name instead of the id
child: Text(m.name),
);
})
.toList(),
);
}
If you want three dropdowns, you would have to create three DropdownButton! You can find more information in the documentation!

How do I encode List<Object> to save to prefs.setStringList in Flutter?

This question which I found here is working for me for encoding an Object to a String in order to save to prefs, but how would I convert this code to encode a List of Objects?
import 'dart:convert';
void main() {
final String encodedData = Music.encode([
Music(id: 1, ...),
Music(id: 2, ...),
Music(id: 3, ...),
]);
final List<Music> decodedData = Music.decode(encodedData);
print(decodedData);
}
class Music {
final int id;
final String name, size, rating, duration, img;
bool favorite;
Music({
this.id,
this.rating,
this.size,
this.duration,
this.name,
this.img,
this.favorite,
});
factory Music.fromJson(Map<String, dynamic> jsonData) {
return Music(
id: jsonData['id'],
rating: jsonData['rating'],
size: jsonData['size'],
duration: jsonData['duration'],
name: jsonData['name'],
img: jsonData['img'],
favorite: false,
);
}
static Map<String, dynamic> toMap(Music music) => {
'id': music.id,
'rating': music.rating,
'size': music.size,
'duration': music.duration,
'name': music.name,
'img': music.img,
'favorite': music.favorite,
};
static String encode(List<Music> musics) => json.encode(
musics
.map<Map<String, dynamic>>((music) => Music.toMap(music))
.toList(),
);
static List<Music> decode(String musics) =>
(json.decode(musics) as List<dynamic>)
.map<Music>((item) => Music.fromJson(item))
.toList();
}
Someone commented that you just need to create a List of Maps, but I just can't get my head around what that means. Please show me using this code.
It's okay both setStringList, setString to store list of objects. But for me, the second one, encoding the whole list once is better
With setStringList
var encodedMusic1 = json.encode(Music(id: 1, ...).toMap());
var encodedMusic2 = json.encode(Music(id: 2, ...).toMap());
List<String> list = [encodedMusic1, encodedMusic2];
prefs.setStringList('key', list);
With setString
var encodedListOfMusic = Music.encode([Music(id: 1, ...), Music(id: 2, ...),]);
prefs.setString('key', encodedListOfMusic);

How to convert data from json to List<Object> in Flutter

I need to obtain a list of Articles(a custom object) from a realtime database in Firebase. I first decode my data from a json data type. Then I try to convert it into a list using this line of code:
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList();
However, this gives a syntax error of "The argument type 'Article Function(Map<dynamic,dynamic>)' can't be assigned to the parameter type 'dynamic Function(Article)'." I have included the code I use to fetch an Article(the custom object) as well as the factory method for the class.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
\\Factory Method
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
author: json['author'],
date: json['date'],
imageUrl: json['imageUrl'],
modalities: json['modalities'],
);
}
I make an example with something like a json response.
void main() {
//this is an example like a json response
List<Map<String, dynamic>> articleResponse = [
{
"id":"1",
"name":"test1"
},
{
"id":"2",
"name":"test2"
}
];
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList();
print('${articles.length} articles in the list!! use to render de ui list');
}
class Article{
String id;
String name;
Article({this.id,this.name});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
name: json['name'],
);
}
}
basically you need to change your method to get articles with this.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
you can use JsonToDart
this is create a class for parse your complex json data
paste json and get class of model
you can overrride toString in your model like:
#override
String toString() {
return '{
id: $id,
title: $title,
author: $author,
date: $date,
imageUrl: $imageUrl,
modalities: $modalities
}';
}
and override toMap :
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'title': title,
'author': author,
'date': date,
'imageUrl': imageUrl,
'modalities': modalities,
};
}
and you can use serialization that. this can help you