{"data":[{"id":"32f","regionName":"Korea","companyName":"Machine","catDealerCode":null},{"id":"cbb","regionName":"Korea","companyName":"KR","catDealerCode":null},{"id":"b6125b0e-5ec9",,"regionName":"China","companyName":"CHN","catDealerCode":null}],"code":0,"message":null}
I have data like the one you see above. I extract data according to the companyName. but some countries don't have data. I want to create an if else case within this.but no matter what I do when I say element == null it doesn't accept. Does anyone know where I am doing wrong? How should I create an if else for empty data?
onTap: () async {
List<Country> country =
await fetchList(
snapshot.data.code);
country.forEach((element) {
if(element.companyName == null){
print('element is empty');
}else{
print('Here ${element.companyName}');
}
});
},
And here's my country list data;
{"data":[{{"code":"KR","name":"Korea","isActive":true,"id":"71"},{"code":"RU","name":"Rusia","isActive":true,"id":"3c"},{"code":"Ch","name":"China","isActive":true,"id":"86"}],"code":0,"message":null}
class Country {
String id;
String companyCode;
String countryCode;
String countryId;
String regionName;
String companyName;
Null catDealerCode;
Country(
{this.id,
this.companyCode,
this.countryCode,
this.countryId,
this.regionName,
this.companyName,
this.catDealerCode});
Couuntry.fromJson(Map<String, dynamic> json) {
id = json['id'];
companyCode = json['companyCode'];
countryCode = json['countryCode'];
countryId = json['countryId'];
regionName = json['regionName'];
companyName = json['companyName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['companyCode'] = this.companyCode;
data['countryCode'] = this.countryCode;
data['countryId'] = this.countryId;
data['regionName'] = this.regionName;
data['companyName'] = this.companyName;
return data;
}
}
I would go with null-aware operator:
onTap: () async {
List<Country> country =
await fetchList(
snapshot.data.code);
country?.forEach((element) {
if(element?.companyName == null){
print('element is empty');
}else{
print('Here ${element.companyName}');
}
});
},
Related
Hello i'm working on flutter project .
I have a class :
class Data {
RevisionInProgress revisionInProgress;
Data({this.revisionInProgress});
Data.fromJson(Map<String, dynamic> json) {
revisionInProgress = json['revision in progress'] != null
? new RevisionInProgress.fromJson(json['revision in progress'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.revisionInProgress != null) {
data['revision in progress'] = this.revisionInProgress.toJson();
}
return data;
}
}
class Datum {
int id;
int boxId;
int userId;
String revisionType;
String revisionDate;
String revisionLocation;
String revisionTitle;
int kilometragePourVidange;
int repeatRevision;
int revisionStatus;
String kilometrageLastVidange;
int kilometrageRevision;
String createdAt;
String updatedAt;
Datum(
{this.id,
this.boxId,
this.userId,
this.revisionType,
this.revisionDate,
this.revisionLocation,
this.revisionTitle,
this.kilometragePourVidange,
this.repeatRevision,
this.revisionStatus,
this.kilometrageLastVidange,
this.kilometrageRevision,
this.createdAt,
this.updatedAt});
Datum.fromJson(Map<String, dynamic> json) {
id = json['id'];
boxId = json['box_id'];
userId = json['user_id'];
revisionType = json['revision_type'];
revisionDate = json['revision_date'];
revisionLocation = json['revision_location'];
revisionTitle = json['revision_title'];
kilometragePourVidange = json['kilometrage_pour_vidange'];
repeatRevision = json['repeat_revision'];
revisionStatus = json['revision_status'];
kilometrageLastVidange = json['kilometrage_last_vidange'];
kilometrageRevision = json['Kilometrage_revision'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['box_id'] = this.boxId;
data['user_id'] = this.userId;
data['revision_type'] = this.revisionType;
data['revision_date'] = this.revisionDate;
data['revision_location'] = this.revisionLocation;
data['revision_title'] = this.revisionTitle;
data['kilometrage_pour_vidange'] = this.kilometragePourVidange;
data['repeat_revision'] = this.repeatRevision;
data['revision_status'] = this.revisionStatus;
data['kilometrage_last_vidange'] = this.kilometrageLastVidange;
data['Kilometrage_revision'] = this.kilometrageRevision;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
After assigning values:
Datum datum = Datum();
void setRevision() async {
print(_EmplacementController.text);
print(_DateController.text);
print(status.toString());
if (_formKey.currentState.validate()) {
datum.revisionType = status.toString();
datum.revisionTitle = _eventController.text;
datum.revisionDate = _DateController.text;
datum.revisionLocation = _EmplacementController.text;
datum.kilometragePourVidange = num.parse(_KilometrageController.text);
datum.repeatRevision = status1;
datum.kilometrageRevision =
num.parse(_Kilometrage_revisionController.text);
print(datum.revisionDate);
print(datum.revisionLocation);
revisionApi
.setRevision(
datum.revisionTitle,
datum.revisionType,
datum.revisionDate,
datum.revisionLocation,
datum.repeatRevision,
datum.kilometrageRevision,
datum.kilometragePourVidange,
)
.then((data) {
if (data != null) {
}
}).catchError((error) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(error.toString())));
});
setState(() {});
Navigator.pop(context);
//
}
}
My problem is when i inspect _EmplacementController.text before assign => it show me the correct value . but if i inspect datum.revisionDate after assign ==> it show me nothing .
datum.revisionDate ==> empty
datum.revisionLocation ==> empty
How i can correct it ?
thanks in advance
If your form is validated then you have to save the form.
bool _validateAndSaveForm() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
if (_validateAndSaveForm()) {
datum.revisionType = status.toString();
datum.revisionTitle = _eventController.text;
datum.revisionDate = _DateController.text;
datum.revisionLocation = _EmplacementController.text;
datum.kilometragePourVidange = num.parse(_KilometrageController.text);
datum.repeatRevision = status1;
datum.kilometrageRevision =
num.parse(_Kilometrage_revisionController.text);
I'm new to flutter and despite my research I can't find the answers. How to update the values of a class according to a dynamic variable.
For example in my User class I want to update the salary of my User according to a map. How to call the key to update the class ?
My class :
class Users{
List<User> user;
Users({this.user});
Users.fromJson(Map<String, dynamic> json) {
if (json['user'] != null) {
user= new List<User>();
json['user'].forEach((v) {
user.add(new User.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user!= null) {
data['user'] = this.user.map((v) => v.toJson()).toList();
}
return data;
}
#override
String toString() {
return '{${this.user}}';
}
}
class User{
String name;
int gender;
num salary;
User(
{this.name,
this.gender,
this.salary,
});
User.fromJson(Map<String, dynamic> json) {
name= json['name'];
gender= json['gender'];
salary= json['salary'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['gender'] = this.gender;
data['salary'] = this.salary;
return data;
}
#override
String toString() {
return '{ '
'${this.name},'
'${this.gender},'
'${this.salary},'
'}';
}
}
Here the function that calculate the new salary of my User and update this.
func_OrderedUsers(List<User> users)
{
List<User> _UsersInOrder;
if (users.length > 0)
{
users.forEach((user)
{
Map _params = {
"salary" : func_CalculateNewSalary(user)
};
func_UpdateItem(user, _params);
});
//... some code
}
And My function UpdateItem :
func_UpdateItem(var item, Map params)
{
if(params != null){
params.forEach((key, value)
{
if(value != null){
// Here is my problem !
// How to use the key variable ?
item.salary = value; // If I write directly the parameter it works (salary)
}
});
}
return item;
}
What you're trying to do is something that dart:mirrors would do. However, since you seem to be using flutter, this is not available for you to use.
Instead you'll have to manually map each key of your Map to a field in your object, just like in your fromJson constructor. You could add a method that does this within your class. Ex.
void updateFieldsFromMap(Map<String, dynamic> input) {
if(input['name'] != null) name = input['name'];
if(input['gender'] != null) gender = input['gender'];
if(input['salary'] != null) salary = input['salary'];
}
You can try to use factory
factory User.fromJson(Map<String, dynamic> json) {
return new User(
name: data['name'],
gender: data['gender'],
salary: data['salary'],
);
}
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 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
}
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.