I am getting null value of user_id - flutter

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

Related

flutter, how to compare the argument passed (id) equal an element.id ? using getx package

I have Categories, and each category contains multiple and different subcategories.
I passed the Id of Categories to the other screen.
First Screen:
onTap: (() => Get.to(const CategoryDetails(), arguments: {
"id":" ${categoriesController.cat!.elementAt(i).sId.toString()} ", })),
ArgumentController
import 'package:get/get.dart';
class ArgumentController extends GetxController {
String? id;
#override
void onInit() {
id = Get.arguments['id'];
super.onInit();
}
}
View File
class _CategoryDetailsState extends State<CategoryDetails> {
int selectedCategoryIndex = 0;
CategoriesController categoriesController = Get.put(CategoriesController());
#override
void initState() {
super.initState();
categoriesController.getCategoriesFromApi();
}
#override
Widget build(BuildContext context) {
ArgumentController controller = Get.put(ArgumentController());
debugPrint(controller.id);
return Scaffold(
appBar: AppBar(
title: const Text("Category Details"),
),
body: Column(
children: [
Text("${controller.id}"),
const Text("data"),
ListView.builder(itemBuilder: (context, index) {
return Column(
children: [
Text(categoriesController.cat!
.elementAt(index)
.subcategories!
.elementAt(selectedCategoryIndex)
.name
.toString()),
],
);
})
],
),
);
}
}
Controller file:
import 'dart:convert';
import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../model/categoriesmodel.dart' as categories_model;
class CategoriesController extends GetxController {
Iterable<categories_model.Response>? cat;
var isDataLoading = false.obs;
getCategoriesFromApi() async {
try {
isDataLoading(true);
http.Response response = await http.post(
Uri.tryParse('-----')!,
headers: {
HttpHeaders.authorizationHeader: '-------',
});
if (response.statusCode == 200) {
var result = jsonDecode(response.body);
cat = categories_model.Categories.fromJson(result).response;
} else {}
} catch (e) {
debugPrint("Error while getting Data $e");
} finally {
isDataLoading(false);
}
}
}
Categoriesmodel file
class Categories {
String? status;
List<Response>? response;
Categories({this.status, this.response});
Categories.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['response'] != null) {
response = <Response>[];
json['response'].forEach((v) {
response!.add(Response.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
if (response != null) {
data['response'] = response!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Response {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
String? icon;
String? logo;
int? itemsCount;
String? lang;
List<Subcategories>? subcategories;
Response(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.icon,
this.logo,
this.itemsCount,
this.lang,
this.subcategories});
Response.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
icon = json['icon'];
logo = json['logo'];
itemsCount = json['itemsCount'];
lang = json['lang'];
if (json['subcategories'] != null) {
subcategories = <Subcategories>[];
json['subcategories'].forEach((v) {
subcategories!.add(Subcategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['icon'] = icon;
data['logo'] = logo;
data['itemsCount'] = itemsCount;
data['lang'] = lang;
if (subcategories != null) {
data['subcategories'] =
subcategories!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Subcategories {
String? sId;
String? name;
bool? isForAccessories;
String? slug;
List<void>? liveTranslations;
int? itemsCount;
String? lang;
Subcategories(
{this.sId,
this.name,
this.isForAccessories,
this.slug,
this.liveTranslations,
this.itemsCount,
this.lang});
Subcategories.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
isForAccessories = json['isForAccessories'];
slug = json['slug'];
// if (json['liveTranslations'] != null) {
// liveTranslations = <Null>[];
// json['liveTranslations'].forEach((v) {
// liveTranslations!.add(Null.fromJson(v));
// });
// }
itemsCount = json['itemsCount'];
lang = json['lang'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['_id'] = sId;
data['name'] = name;
data['isForAccessories'] = isForAccessories;
data['slug'] = slug;
// if (liveTranslations != null) {
// data['liveTranslations'] =
// liveTranslations!.map((v) => v.toJson()).toList();
// }
data['itemsCount'] = itemsCount;
data['lang'] = lang;
return data;
}
}
The problem is in selectedCategoryIndex, how to express that
selectedCategoryIndex == categoriesController.Where((element) => element.sid == the argument passed);
note that it's not acceptable categoriesController.Where..
I just assumed your question to be what I think and posting this solution.
selectedCategoryIndex ==
categoriesController.cat.singleWhere((element) => element.id == id).sId;

How to send data through patch request in flutter

I am facing issue in sending the below data as a patch request.
The issue I am facing is I am not able to pass the Detail object data within another object(AddPerson) hence if you could please help me resolve this issue.
Additionally the data is being captured correctly but the format of the data as shown in sample data is not being captured.
Hence if you could please help in resolving this issue.
Below is the code
Model.dart
class AddPerson {
String? personId;
String? personName;
List<Details>? details;
AddPerson(
{this.personId, this.personName, this.details});
AddPerson.fromJson(Map<String, dynamic> json) {
personId = json['personId'];
personName = json['personName'];
if (json['details'] != null) {
details = <Details>[];
json['details'].forEach((v) {
details!.add(new Details.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['personId'] = this.personId;
data['personName'] = this.personName;
if (this.details != null) {
data['details'] = this.details!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Details with ChangeNotifier {
String? type;
String? price;
String? notificationId;
Details({this.type, this.price, this.notificationId});
Details.fromJson(Map<String, dynamic> json) {
type = json['type'];
price = json['price'];
notificationId = json['notification_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['price'] = this.price;
data['notification_id'] = this.notificationId;
return data;
}
}
Provider.dart
Future<void> updateAddPerson(
List<AddPerson> newNotification, List<Details> s) async {
Map<String, String> headers = {
// "Content-Type": "charset=utf-8",
"Content-type": "application/json"
};
var uri = Uri.parse('http://localhost:3001/users/update/person');
try {
var request = http.MultipartRequest('PATCH', uri);
request.headers.addAll(headers);
for (int i = 0; i <= newNotification.length - 1; i++) {
request.fields['personId[$i]'] = '${newNotification[i].personId}';
request.fields['personName[$i]'] = '${newNotification[i].personName}';
for (int m = 0; m <= s.length - 1; m++) {
request.fields['notification_id[$m]'] = '${s[m].notificationId}';
request.fields['type[$m]'] = '${s[m].type}';
request.fields['price[$m]'] = '${s[m].price}';
}
}
var response = await request.send();
print(response.statusCode);
if (response.statusCode == 201) {
notifyListeners();
} else {
print('invalid data ');
}
} catch (error) {
print('NA');
}
}
Sample result
[
{
"personId": "1",
"personName":"Akash”,
"details": [
{
"notification_id": 1,
"type": “SUV”,
"price": "200"
},
{
"notification_id": 2,
"type": “SUV”,
"price": "250"
}
]
}
]

FutureBuilder snapshot.hasData always return false

i'm new to learning darts and flutter i'm making code to display data with FutureBuilder, in console window i got the response i want, but the snapshot.hashData code always returns false
Myclass model
class ResponseDataBarang {
int? _kode;
String? _pesan;
List<Data>? _data;
ResponseDataBarang({int? kode, String? pesan, List<Data>? data}) {
if (kode != null) {
this._kode = kode;
}
if (pesan != null) {
this._pesan = pesan;
}
if (data != null) {
this._data = data;
}
}
int? get kode => _kode;
set kode(int? kode) => _kode = kode;
String? get pesan => _pesan;
set pesan(String? pesan) => _pesan = pesan;
List<Data>? get data => _data;
set data(List<Data>? data) => _data = data;
ResponseDataBarang.fromJson(Map<String, dynamic> json) {
_kode = json['kode'];
_pesan = json['pesan'];
if (json['data'] != null) {
_data = <Data>[];
json['data'].forEach((v) {
_data!.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['kode'] = this._kode;
data['pesan'] = this._pesan;
if (this._data != null) {
data['data'] = this._data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? _kdBrg;
String? _nmBrg;
Data(
{String? kdBrg,
String? nmBrg,
}) {
if (kdBrg != null) {
_kdBrg = kdBrg;
}
if (nmBrg != null) {
_nmBrg = nmBrg;
}
}
String? get kdBrg => _kdBrg;
set kdBrg(String? kdBrg) => _kdBrg = kdBrg;
String? get nmBrg => _nmBrg;
Data.fromJson(Map<String, dynamic> json) {
_kdBrg = json['KdBrg'];
_nmBrg = json['NmBrg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['KdBrg'] = _kdBrg;
data['NmBrg'] = _nmBrg;
return data;
}
}
My request
i am confused for the json format as generated what return value is suitable for my method request
Future<ResponseDataBarang> ambilDataBarang() async {
Dio apiClient=ApiClient().init();
final response=await apiClient.post('http://192.168.1.8/aplikasikasir/data_barang.php', data: FormData.fromMap(({
"NmUser":"T",
})));
return ResponseDataBarang.fromJson(response.data);
}
}
Response i got
{"kode":1,"pesan":"Data Tersedia","data":[{"KdBrg":"170164017","NmBrg":"ST PP HONGNIE SANDAL","Harga":"38000","Stock_Akhir":"0","Sat_1":"PT","Sat_2":"","Sat_3":"","Sat_4":"","Isi_2":"0","Isi_3":"0","Isi_4":"0","KdSupl":"","NmSupl":"","Ket1":""}]}

why http.response response inaktive?

on my code repsonse.body or response.statuscode does not work. What is wrong here?
class Kategori {
int? id;
String? name;
Kategori({
this.id,
this.name
});
Future<List<Categories>> getAllCategories() async {
http.Response response = await http.get(Uri.parse('https://www.catshops.com/getAllCategories'));
List<Categories> list = [];
return getAllCategories();
}
try {
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
for (var map in map['categories']) {
list.add(Categories(id: map['id'], name: map['name']));
}
}
} catch (e, _) {
Btw try statement does not work, either
try this
class Categories {
int? id;
String? name;
Categories({this.id, this.name});
}
Future<List<Categories>> getAllCategories() async {
http.Response response =
await http.get(Uri.parse('https://www.catshops.com/getAllCategories'));
List<Categories> list = [];
try {
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
for (var map in map['categories']) {
list.add(Categories(id: map['id'], name: map['name']));
}
}
} catch (e, _) {}
return list;
}
you can use this :
class Category {
int id;
String name;
Category({this.id, this.name});
Category.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Future<List<Category>> getAllCategory() async {
http.Response response =
await http.get(Uri.parse('https://www.catshops.com/getAllCategories'));
List<Category> list = [];
try {
if (response != null && response.statusCode == 200) {
list = (response.data as List)
.map((item) => Category.fromJson(item))
.toList();
}
} catch (e) {
print(e.toString());
}
return list;
}
you can create you'r class (in dart struct) with this website.

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.