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);
Related
How do I retrieve the information in the address? Attempted to retrieve information I can fetch but the Items class part is not fetching the address part. I'm practicing the fetch api.
I'm not sure if what I'm doing is correct. or may be stuck with some part of the problem i try to fix please help me
List<Items> _list = [];
List<Items> _search = [];
var loading = false;
Future fetchMos() async {
setState(() {
loading = true;
});
_list.clear();
var client = http.Client();
String mosUrl =
'';
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': ''};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var data = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
setState(() {
for (Map i in data) {
_list.add(Items.fromJson(i));
loading = false;
}
});
}
}
This is class model
class Items {
String? custnum;
String? name;
List<Address>? address;
Items({this.custnum, this.name, this.address});
Items.fromJson(json) {
custnum = json['custnum'];
name = json['name'];
if (json['address'] != null) {
address = <Address>[];
json['address'].forEach((v) {
address!.add(new Address.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['custnum'] = this.custnum;
data['name'] = this.name;
if (this.address != null) {
data['address'] = this.address!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Address {
int? shipto;
String? addr1;
String? thanon;
String? tambon;
String? amphur;
String? provCode;
String? province;
String? country;
String? phone;
String? email;
String? postcode;
String? contact;
String? latitude;
String? longitude;
String? fax;
String? soi;
Address(
{this.shipto,
this.addr1,
this.thanon,
this.tambon,
this.amphur,
this.provCode,
this.province,
this.zipcode,
this.country,
this.phone,
this.email,
this.postcode,
this.contact,
this.latitude,
this.longitude,
this.fax,
this.soi});
Address.fromJson(json) {
shipto = json['shipto'];
addr1 = json['addr1'];
thanon = json['thanon'];
tambon = json['tambon'];
amphur = json['amphur'];
provCode = json['prov_code'];
province = json['province'];
zipcode = json['zipcode'];
country = json['country'];
phone = json['phone'];
email = json['email'];
postcode = json['postcode'];
contact = json['contact'];
latitude = json['latitude'];
longitude = json['longitude'];
fax = json['fax'];
soi = json['soi'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['shipto'] = this.shipto;
data['addr1'] = this.addr1;
data['thanon'] = this.thanon;
data['tambon'] = this.tambon;
data['amphur'] = this.amphur;
data['prov_code'] = this.provCode;
data['province'] = this.province;
data['zipcode'] = this.zipcode;
data['phone'] = this.phone;
data['email'] = this.email;
data['postcode'] = this.postcode;
data['contact'] = this.contact;
data['longitude'] = this.longitude;
data['fax'] = this.fax;
data['soi'] = this.soi;
return data;
}
}
var data =json.decode(response.body);
for (var i in data['items']) {
_list.add(Items.fromJson(i));
loading = false;
}
setState(() { });
Future<bool> login({username, password}) async {
var api = API();
_status = LoginStatus.loading;
notifyListeners();
var url = Uri.parse(api.baseUrl + api.auth);
final response = await http.post(
url,
body: jsonEncode({
"identifier": "$username",
"password": "$password",
}),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
parsed
.map<UserModel>((json) => UserModel.fromJson(json))
.toList();
final token = jsonDecode(response.body)['jwt'];
print(token);
await saveToken(token);
return true;
} else {
_status = LoginStatus.error;
_error = response.body;
notifyListeners();
return false;
}
}
Code Screen Shot
How Should I save this parsed JSON to UserModel? I have encountered many problems and figured out many things on my own but I am not yet able to add data to the model.
By the way I am using strapi as a back end and every api is working. And I amso use a website called json to dart converter so that my models are correct(As I Assume).
Please help !!!!!!!!!!!!
UserModel
class UserModel {
User user;
UserModel({this.user});
UserModel.fromJson(Map<String, dynamic> json) {
user = json['user'] != null ? new User.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class User {
int id;
String username;
String email;
String provider;
bool confirmed;
bool blocked;
Role role;
String displayName;
String createdAt;
String updatedAt;
Avatar avatar;
List<UserCategories> userCategories;
User(
{this.id,
this.username,
this.email,
this.provider,
this.confirmed,
this.blocked,
this.role,
this.displayName,
this.createdAt,
this.updatedAt,
this.avatar,
this.userCategories});
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
username = json['username'];
email = json['email'];
provider = json['provider'];
confirmed = json['confirmed'];
blocked = json['blocked'];
role = json['role'] != null ? new Role.fromJson(json['role']) : null;
displayName = json['displayName'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
avatar =
json['avatar'] != null ? new Avatar.fromJson(json['avatar']) : null;
if (json['user_categories'] != null) {
userCategories = new List<UserCategories>();
json['user_categories'].forEach((v) {
userCategories.add(new UserCategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['username'] = this.username;
data['email'] = this.email;
data['provider'] = this.provider;
data['confirmed'] = this.confirmed;
data['blocked'] = this.blocked;
if (this.role != null) {
data['role'] = this.role.toJson();
}
data['displayName'] = this.displayName;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.avatar != null) {
data['avatar'] = this.avatar.toJson();
}
if (this.userCategories != null) {
data['user_categories'] =
this.userCategories.map((v) => v.toJson()).toList();
}
return data;
}
}
class Role {
int id;
String name;
String description;
String type;
Role({this.id, this.name, this.description, this.type});
Role.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
description = json['description'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['description'] = this.description;
data['type'] = this.type;
return data;
}
}
class Avatar {
int id;
String name;
String alternativeText;
String caption;
int width;
int height;
Formats formats;
String hash;
String ext;
String mime;
double size;
String url;
Null previewUrl;
String provider;
Null providerMetadata;
String createdAt;
String updatedAt;
Avatar(
{this.id,
this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt});
Avatar.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
alternativeText = json['alternativeText'];
caption = json['caption'];
width = json['width'];
height = json['height'];
formats =
json['formats'] != null ? new Formats.fromJson(json['formats']) : null;
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
size = json['size'];
url = json['url'];
previewUrl = json['previewUrl'];
provider = json['provider'];
providerMetadata = json['provider_metadata'];
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['name'] = this.name;
data['alternativeText'] = this.alternativeText;
data['caption'] = this.caption;
data['width'] = this.width;
data['height'] = this.height;
if (this.formats != null) {
data['formats'] = this.formats.toJson();
}
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['size'] = this.size;
data['url'] = this.url;
data['previewUrl'] = this.previewUrl;
data['provider'] = this.provider;
data['provider_metadata'] = this.providerMetadata;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Formats {
Thumbnail thumbnail;
Formats({this.thumbnail});
Formats.fromJson(Map<String, dynamic> json) {
thumbnail = json['thumbnail'] != null
? new Thumbnail.fromJson(json['thumbnail'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.thumbnail != null) {
data['thumbnail'] = this.thumbnail.toJson();
}
return data;
}
}
class Thumbnail {
String name;
String hash;
String ext;
String mime;
int width;
int height;
double size;
Null path;
String url;
Thumbnail(
{this.name,
this.hash,
this.ext,
this.mime,
this.width,
this.height,
this.size,
this.path,
this.url});
Thumbnail.fromJson(Map<String, dynamic> json) {
name = json['name'];
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
width = json['width'];
height = json['height'];
size = json['size'];
path = json['path'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['width'] = this.width;
data['height'] = this.height;
data['size'] = this.size;
data['path'] = this.path;
data['url'] = this.url;
return data;
}
}
class UserCategories {
int id;
String categoryName;
int usersPermissionsUser;
String publishedAt;
String createdAt;
String updatedAt;
UserCategories(
{this.id,
this.categoryName,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt});
UserCategories.fromJson(Map<String, dynamic> json) {
id = json['id'];
categoryName = json['categoryName'];
usersPermissionsUser = json['users_permissions_user'];
publishedAt = json['published_at'];
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['categoryName'] = this.categoryName;
data['users_permissions_user'] = this.usersPermissionsUser;
data['published_at'] = this.publishedAt;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
The UserModel.fromJson method will only work if the response.body content is a User, so to fix your issue, instead of using UserModel.fromJson on the response.body json decoded variable, rather use the fromJson() function on data that you are sure will conform to your class definition.
For example:
class User{
final String name;
final String surname;
final String email;
User({this.name, this.surname, this.email});
factory User.fromJson(Map<String,dynamic> json){
return User(
'name': json['name'],
'surname': json['surname'],
'email': json['email']
);
}
}
The json response that is recieved from the api:
{
"name" : "John",
"surname": "Smith",
"email": "johnsmith#mail.com"
}
In your function, decode response and cast to the User model class:
final parsed = jsonDecode(response.body); // or Map<String,dynamic> parsed = jsonDecode(response.body);
User user = User.fromJson(parsed)
I'm starter in flutter . I would like to fetch data from Complex json using API . Using postman my response body contain publication object and inside it i have i list of objects. . firstly i created Publication model and i try to use it for fetching data but snapshot.data is still NULL . any help please ??
#override
void initState() {
getproduct(widget.idproduct);
super.initState();
}
Future<Publication> getproduct(int id) async {
var response = await Network().getData('/publication/show/$id');
return Publication.fromJson(json.decode(response.body['publication']));
}
child: SingleChildScrollView(
child: FutureBuilder<Publication>(
future: getproduct(widget.idproduct),
builder: (BuildContext context, AsyncSnapshot snapshot) {
inspect(snapshot.data);
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
for (int i = 0;
i < snapshot.data.publication.length;
i++)
CommentsList(
comment: snapshot.data.publication[i].comment,
)
],
);
}
and this my Publication Class:
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;
}
}
I got the following error when i print (snapshot) :
and i got this error when inspect(snapshot);
It has error, use snapshot.hasError to handle and show the errorMessage,
and error is in your model/Pojo class, something declared as int but it is String. Please check & compare your response and pojo/model.
Check at 60:58 of the PetDetail.dart file
This might help you
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html#widgets.FutureBuilder.1
in order this line to work
snapshot.data.publication.length;
this line must return an object which must have publication and that must be a list
getproduct(widget.idproduct);
I am trying to build an e-commerce app using flutter and woocommece api.But when i try to press addtocart button this is what i get :
products:List (1 item)
userId:null
hashCode:383444147
runtimeType:Type (CartRequestModel)
i get products but i am not getting userId.
Here is my config.dart:
class Config {
static String key = "ck_xxxxxxxxxxxxxxxxxxxxxxxxxx";
static String secret = "cs_xxxxxxxxxxxxxxxxxxxx7dc9feb";
static String url = "https://gngbd.xyz/wp-json/wc/v3";
static String customerURL = "/customers";
static String tokenUR = "https://gngbd.xyz/wp-json/jwt-auth/v1/token";
static String categoryURL = "/products/categories";
static String productsURL = "/products";
static String todayOffersTagId = "20";
static String addToCartURL = "/addtocart";
static String cartURL = "/cart";
static String userId = "4";
}
Here is my cart_provider.dart :
import 'package:flutter/material.dart';
import 'package:grocerry/api_service.dart';
import 'package:grocerry/models/cart_request_model.dart';
import 'package:grocerry/models/cart_response_model.dart';
class CartProvider with ChangeNotifier {
ApiService apiService;
List<CartItem> _cartItems;
List<CartItem> get CartItems => _cartItems;
double get totalRecords => _cartItems.length.toDouble();
CartProvider() {
apiService = new ApiService();
// ignore: deprecated_member_use
_cartItems = new List<CartItem>();
}
void resetStreams() {
apiService = new ApiService();
// ignore: deprecated_member_use
_cartItems = new List<CartItem>();
}
void addToCart(CartProducts product, Function onCallBack) async {
CartRequestModel requestModel = new CartRequestModel();
// ignore: deprecated_member_use
requestModel.products = new List<CartProducts>();
if (_cartItems == null) resetStreams();
_cartItems.forEach((element) {
requestModel.products.add(new CartProducts(
productId: element.productId, quantity: element.qty));
});
var isProductExists = requestModel.products.firstWhere(
(prd) => prd.productId == product.productId,
orElse: () => null);
if (isProductExists != null) {
requestModel.products.remove(isProductExists);
}
requestModel.products.add(product);
await apiService.addToCart(requestModel).then((cartResponseModel) {
if (cartResponseModel.data != null) {
_cartItems = [];
_cartItems.addAll(cartResponseModel.data);
}
onCallBack(cartResponseModel);
notifyListeners();
});
}
}
Here i tried to build a addtocart function and also called the api_service.dart file
Here is my code for ApiService.dart :
Future<CartResponseModel> addToCart(CartRequestModel model) async {
model.userId = int.parse(Config.userId);
CartResponseModel responseModel;
try {
var response = await Dio().post(
Config.url + Config.addToCartURL,
data: model.toJson(),
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
),
);
if (response.statusCode == 200) {
responseModel = CartResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
// print(e.message);
if (e.response.statusCode == 404) {
print(e.response.statusCode);
} else {
print(e.message);
print(e.request);
}
}
return responseModel;
}
Future<CartResponseModel> getCartItems() async {
CartResponseModel responseModel;
try {
String url = Config.url +
Config.cartURL +
"?user_id=${Config.userId}&consumer_key=${Config.key}&consumer_secret=${Config.secret}";
print(url);
var response = await Dio().post(
url,
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
),
);
if (response.statusCode == 200) {
responseModel = CartResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return responseModel;
}
I have also two model one is for cart Request and another is for cartresponse model i am also providing this code
Here is my CartRequest.dart
class CartRequestModel {
int userId;
List<CartProducts> products;
CartRequestModel({this.userId, this.products});
CartRequestModel.fromJson(Map<String, dynamic> json) {
userId = json['user_id'];
if (json['products'] != null) {
// ignore: deprecated_member_use
products = new List<CartProducts>();
json['products'].forEach((v) {
products.add(new CartProducts.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['user_id'] = this.userId;
if (this.products != null) {
data['products'] = this.products.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartProducts {
int productId;
int quantity;
CartProducts({this.productId, this.quantity});
CartProducts.fromJson(Map<String, dynamic> json) {
productId = json['product_id'];
quantity = json['quantity'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = this.productId;
data['quantity'] = this.quantity;
return data;
}
}
Here is my CartResponse Model and down below is my code please check if needed :
class CartResponseModel {
bool status;
List<CartItem> data;
CartResponseModel({this.status, this.data});
CartResponseModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
// ignore: deprecated_member_use
data = new List<CartItem>();
json['data'].forEach((v) {
data.add(new CartItem.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItem {
int productId;
String productName;
String productRegularPrice;
String productsalePrice;
String thumbNail;
int qty;
double lineTotal;
double lineSubTotal;
CartItem(
{this.productId,
this.productName,
this.productRegularPrice,
this.productsalePrice,
this.thumbNail,
this.qty,
this.lineTotal,
this.lineSubTotal});
CartItem.fromJson(Map<String, dynamic> json) {
productId = json['product_id'];
productName = json['product_name'];
productRegularPrice = json['product_regular_price'];
productsalePrice = json['product_sale_price'];
thumbNail = json['thumbnail'];
qty = json['qty'];
lineSubTotal = double.parse(json['line_subtotal'].toString());
lineTotal = double.parse(json['line_total'].toString());
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = this.productId;
data['product_name'] = this.productName;
data['product_regular_price'] = this.productRegularPrice;
data['product_sale_price'] = this.productsalePrice;
data['thumbnail'] = this.thumbNail;
data['qty'] = this.qty;
data['line_subtotal'] = this.lineSubTotal;
data['line_total'] = this.lineTotal;
return data;
}
}
You need to login , then Testing this
{"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}');
}
});
},