Flutter get value in object list - flutter

In my Home.dart
static _getList() async {
Network network = Network();
final List list = await network.getData();
print("jsonString");
print(list);
return list;
}
Result in console:
flutter: [{id: 1, calc: 000100, name: Test, date: 2018-03-29 12:45:26.9830000}]
I need to get the id's and names of this object and generate a list, to be read

You need to convert your json data to objects.
There are tools to help you generating object from json like json2Dart. The result is :
class MyObject {
int id;
String calc;
String name;
String date;
MyObject({this.id, this.calc, this.name, this.date});
MyObject.fromJson(Map<String, dynamic> json) {
id = json['id'];
calc = json['calc'];
name = json['name'];
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['calc'] = this.calc;
data['name'] = this.name;
data['date'] = this.date;
return data;
}
#override
String toString() {
return '$id';
}
}
You need to iterate over your list from getData() and call MyObject.fromJson() from each occurence :
var myObjetcs = [];
for (var item in list) {
myObjetcs.add(MyObject.fromJson(item));
}
//Now, do what you want with myObjects
Hope it will help you

Related

How return a Future<List<PokemonModel>> to use data in widgets?

My PokemonModel and Results class, i wan't return a List
class PokemonModel {
int count;
String next;
String previous;
List<Results> results;
PokemonModel({this.count, this.next, this.previous, this.results});
PokemonModel.fromJson(Map<String, dynamic> json) {
count = json['count'];
next = json['next'];
previous = json['previous'];
if (json['results'] != null) {
results = [];
json['results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['count'] = this.count;
data['next'] = this.next;
data['previous'] = this.previous;
if (this.results != null) {
data['results'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String name;
String url;
Results({this.name, this.url});
Results.fromJson(Map<String, dynamic> json) {
name = json['name'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['url'] = this.url;
return data;
}
}
I try use this on repository, i'll need ['next'], ['previous'] and results data to use in widgets but i cannot convert the data to a list of PokemonModel.
That's my current repository where i try get data.
class PokemonRepository implements IPokemonRepository {
Dio _dio;
final String url = 'https://pokeapi.co/api/v2/pokemon/';
PokemonRepository([Dio dio]) : _dio = dio ?? Dio();
#override
Future<List<PokemonModel>> getPokemons() async {
final response = await _dio.get(url);
final poke = PokemonModel.fromJson(response.data);
//how parse and return a list of pokemonmodel?
}
}
There are a couple of ways you can do it.
// method 1 (declarative/functional programming)
final List<PokemonModel> myList = response
.map<PokemonModel>((item) => PokemonModel.fromJson(item))
.toList();
return myList;
or
// method 2 (imperative)
final myList2 = <PokemonModel>[];
for (final Map<String, dynamic> item in response) {
myList2.add(PokemonModel.fromJson(item));
}
return myList2;
I've seen it done both ways. Both return the same result.

Adding firestore subcollection fields into List

i am trying to add the fields of a subcollection into reviewsList. May i know how should I do that in the //To add to List// part?
The 'Reviews' collection contains 2 subcollections namely '1' and '2'. Both '1' and '2' each contain a map of 4 fields.
Below are the codes and screenshot of firestore:
List<dynamic> reviewsList = [];
Future _getReviews() async{
firestore.collection('shops').doc(widget.shop.id).collection('reviews').get()
.then((reviews){
reviews.docs.forEach((result) {
firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id)
.get().then((reviewDocumentSnapshot) {
// To add to List //
});
});
});
}
the issue is related to misunderstanding of async. change your function as
Future _getReviews() async{
var reviews = await firestore.collection('shops').doc(widget.shop.id).collection('reviews').get();
reviews.docs.forEach((result) {
var reviewDocumentSnapshot= await firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id);
//add this snapshot to list.
reviewsList[your_object.fromJson(reviewDocumentSnapshot)];
});
}
and your model class will be
class your_model {
String name;
String review;
int star;
String uid;
your_model({this.name, this.review, this.star, this.uid});
your_model.fromJson(Map<String, dynamic> json) {
name = json['name'];
review = json['review'];
star = json['star'];
uid = json['uid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['review'] = this.review;
data['star'] = this.star;
data['uid'] = this.uid;
return data;
}
}

Unable to access list item inside a class

I've been wrapping my head around this issue for the past 2 hours (keep in mind that I'm new to Flutter). I'm trying to check if I've set up everything properly for getting a movie list from OMDB. Everything seems okay except the fact that I don't know how to access something inside a list ie. originalTitle.
This is the model:
class MovieItem {
int page;
int totalResults;
int totalPages;
List<Results> results;
MovieItem({this.page, this.totalResults, this.totalPages, this.results});
MovieItem.fromJson(Map<String, dynamic> json) {
page = json['page'];
totalResults = json['total_results'];
totalPages = json['total_pages'];
if (json['results'] != null) {
results = new List<Results>();
json['results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['page'] = this.page;
data['total_results'] = this.totalResults;
data['total_pages'] = this.totalPages;
if (this.results != null) {
data['results'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String posterPath;
int id;
String originalLanguage;
String originalTitle;
String title;
Results(
{this.posterPath,
this.id,
this.originalLanguage,
this.originalTitle,
this.title,});
Results.fromJson(Map<String, dynamic> json) {
posterPath = json['poster_path'];
id = json['id'];
originalLanguage = json['original_language'];
originalTitle = json['original_title'];
title = json['title'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['poster_path'] = this.posterPath;
data['id'] = this.id;
data['original_language'] = this.originalLanguage;
data['original_title'] = this.originalTitle;
data['title'] = this.title;
return data;
}
}
You are attempting to call a property on a List<Result> instead of Result. The property you are attempting to access exists on Result ... if there is a List of Result objects, what do you expect to return with movieItem.results.originalTitle? There could be any number of Result object with possibly different titles? If you just want to print them all out:
Future<MovieItem> movieItem() async {
var movieItem = await
client.movieItem();
movieItem.results.forEach((result) => print(result.originalTitle));
return movieItem;
}
The forEach will allow you to call the property and print it on every Result in the list
Your movieItem model class has list of result objects. So when you call the client.movieItem method the you get a MovieItem Object, and it you want to print the specific result item then just do this
print(movieItem.results[0].originalTitle)
and if you want to access all the objects from the result list then using for loop you can achieve it
for(int i=0;i<movieItem.results.length;i++)
{
print(movieItem.results[i].originalTitle);
}

I want to retrive each entity from following data in flutter

I want to sort each entity from following data in flutter
i.e enrollment_no,nationality,mother this data is coming from api
"personal":
"{\"enrollment_no\":\"1701\",
\"nationality\":\"INDIAN\",
\"driver_mobile\":\"-\",
\"mother\":\"JAGRUTIBAHEN SHRIKANT SONI\",
\"email\":\"SHRIKANT206#YAHOO.CO.IN\",
\"student_photo\":\"/container/school_data/BRS/photo/Student/1701.jpg\",
\"name\":\"NEYSA SHRIKANT SONI\",
\"mother_mobile\":\"+971507603564\",
\"father_mobile\":\"+971503171294\",
\"father\":\"SHRIKANT INDUKANT SONI\"}",
//I trying following code to sort data but can't achieve
if(personal == data['personal']) {
for (int i = 0; i < data['personal'].length; i++)
{
arrayp = personal;
print(arrayp);
var array1=arrayp[0]['father'];
print(array1);
}
}
1. Your JSON from API
{
"personal":
{
"enrollment_no": "1701",
"nationality": "INDIAN",
"driver_mobile": "-",
"mother": "JAGRUTIBAHEN SHRIKANT SONI",
"email": "SHRIKANT206#YAHOO.CO.IN",
"student_photo": "/container/school_data/BRS/photo/Student/1701.jpg",
"name": "NEYSA SHRIKANT SONI",
"mother_mobile": "+971507603564",
"father_mobile": "+971503171294",
"father": "SHRIKANT INDUKANT SONI"
}
}
2. Go To https://javiercbk.github.io/json_to_dart/
Convert your Json to Dart Classes.
class Personal {
PersonalData personal;
Personal({this.personal});
factory Personal.fromJson(Map<String, dynamic> json) {
return Personal(
personal: json['personal'] != null ?
PersonalData.fromJson(json['personal']) : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.personal != null) {
data['personal'] = this.personal.toJson();
}
return data;
}
}
class PersonalData {
String driver_mobile;
String email;
String enrollment_no;
String father;
String father_mobile;
String mother;
String mother_mobile;
String name;
String nationality;
String student_photo;
PersonalData({this.driver_mobile, this.email, this.enrollment_no, this.father, this.father_mobile, this.mother, this.mother_mobile, this.name, this.nationality, this.student_photo});
factory PersonalData.fromJson(Map<String, dynamic> json) {
return PersonalData(
driver_mobile: json['driver_mobile'],
email: json['email'],
enrollment_no: json['enrollment_no'],
father: json['father'],
father_mobile: json['father_mobile'],
mother: json['mother'],
mother_mobile: json['mother_mobile'],
name: json['name'],
nationality: json['nationality'],
student_photo: json['student_photo'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['driver_mobile'] = this.driver_mobile;
data['email'] = this.email;
data['enrollment_no'] = this.enrollment_no;
data['father'] = this.father;
data['father_mobile'] = this.father_mobile;
data['mother'] = this.mother;
data['mother_mobile'] = this.mother_mobile;
data['name'] = this.name;
data['nationality'] = this.nationality;
data['student_photo'] = this.student_photo;
return data;
}
}
3. Now time for you api response
_getResponseFromApi() asyn{
var response = await http.post({your parameters})
var data = Personal.fromJson(json.decode(response.body));
var listOfPersonData = data.personal
}

flutter add data to json only if it does not already exist

I have following Model
product_model.dart
class ProductModel {
String status;
String message;
List<Results> results;
ProductModel({this.status, this.message, this.results});
ProductModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
results = new List<Results>();
json['data'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
if (this.results != null) {
data['data'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String id;
String productCode;
String category;
String title;
String isActive;
Results(
{this.id,
this.productCode,
this.category,
this.title,
this.isActive,
});
Results.fromJson(Map<String, dynamic> json) {
id = json['id'];
productCode = json['product_code'];
category = json['category'];
title = json['title'];
isActive = json['is_active'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_code'] = this.productCode;
data['title'] = this.title;
data['category'] = this.category;
data['is_active'] = this.isActive;
return data;
}
}
I have a functionality to save products to favorites. The favorites will be saved as json in a file.
import 'package:example/utils/favstorage.dart';
import 'package:example/models/product_model.dart';
class FavoriteProducts {
FavoritesStorage storage = FavoritesStorage();
List<ProductModel> favorites = [];
Future addFavorite(ProductModel products) async {
favorites.add(products);
await storage.writeFavorites(favorites);
}
}
I want to add product to favorites only if its not there. How can I update the addFavorite method so that if particular id doesnot exist then only proceed adding to favorites.
I am new to flutter. Can anybody help me on this??
You can use and indexWhere to search your list for an item with the same id, like this:
Future addFavorite(ProductModel products) async {
if(favorites.indexWhere((listProduct) => listProduct.id == products.id) == -1){
favorites.add(products);
await storage.writeFavorites(favorites);
}
}
-1 means there was no item, if there was the item it would have returned it from the list.
Understanding your model:
ProductModel has List
Results has id.
How to see if provided ProductModel can be added to favorite:
Take favorites list and look in List.
in each product model liik in List.
for each Results check if there id is same as any Results in List of provided ProductModel to the method.
If every thing is false, add ProductModel to favorite.
Following is the code for your reference:
Future addFavorite(ProductModel products) async {
bool containsId = favorites.any((ProductModel model){
return model.results.any((Results result){
return products.results.any((Results resultInProducts) => resultInProducts.id == result.id);
});
});
if(!containsId){
favorites.add(products);
await storage.writeFavorites(favorites);
}
}
I hope this helps, in case of any doubt please comment. If this answer helps you then please accept and up-vote the answer.