FutureBuilder snapshot.hasData always return false - flutter

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":""}]}

Related

How to save this nested class in Isar DB Flutter

I have the following 4 classes. In this, only the ProductGroup is saved, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.
product_group.dart
#Collection()
class ProductGroup {
late Id id;
#Index(caseSensitive: false)
late String productGroupName;
final productVariants = IsarLinks<ProductVariant>();
ProductGroup();
ProductGroup.fromJson(Map<String, dynamic> json) {
id = json['Id'];
productGroupName = json['PG'];
if (json['Ps'] != null) {
json['Ps'].forEach((variant) {
productVariants.add(ProductVariant.fromJson(variant));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['PG'] = productGroupName;
data['Ps'] = productVariants.map((variant) => variant.toJson()).toList();
return data;
}
}
product_variant.dart
#Collection()
class ProductVariant {
late Id id;
late String variantName;
final productSizes = IsarLinks<ProductSize>();
ProductVariant();
ProductVariant.fromJson(Map<String, dynamic> json) {
id = json['Id'];
variantName = json['St'];
if (json['Ss'] != null) {
json['Ss'].forEach((v) {
productSizes.add(ProductSize.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['St'] = variantName;
data['Ss'] = productSizes.map((v) => v.toJson()).toList();
return data;
}
}
product_size.dart
#Collection()
class ProductSize {
late Id id;
late String size;
final productColors = IsarLinks<ProductColor>();
ProductSize();
ProductSize.fromJson(Map<String, dynamic> json) {
id = json['Id'];
size = json['S'];
if (json['Cs'] != null) {
json['Cs'].forEach((v) {
productColors.add(ProductColor.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['S'] = size;
data['Cs'] = productColors.map((color) => color.toJson()).toList();
return data;
}
}
product_color.dart
#Collection()
class ProductColor {
late Id id;
late String colorName;
late String colorHexCode;
ProductColor();
ProductColor.fromJson(Map<String, dynamic> json) {
id = json['Id'];
colorName = json['C'];
colorHexCode = json['CC'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['C'] = colorName;
data['CC'] = colorHexCode;
return data;
}
}
I am parsing the json and saving it in Isar
convertJsonToIsar() async {
try {
// For testing purposes, loading Json from assets, in Prod, Json will be fetched from server
final String response = await rootBundle.loadString('assets/pr_dump.json');
final data = await json.decode(response);
List<ProductGroup> productGroupList = [];
data.forEach((item) {
productGroupList.add(ProductGroup.fromJson(item));
});
Isar _isar = getIsar();
_isar.writeTxnSync(() {
_isar.productGroups.putAllSync(productGroupList, saveLinks: true);
});
} catch (e) {
// Handle Error
print('Caught Error');
print(e.toString());
return 0;
}
}
Only the ProductGroup is stored, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.

I am trying to get data from API but having error

This is my model class and I am trying to get all the data but getting error and don't know why.
HomePageModel homePageModelFromJson(String str) => HomePageModel.fromJson(json.decode(str));
String homePageModelToJson(HomePageModel data) => json.encode(data.toJson());
class HomePageModel with ChangeNotifier {
HomePageModel({
this.data,
});
List<Datum>? data;
factory HomePageModel.fromJson(Map<String, dynamic> json) => HomePageModel(
data: List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
schoolid: json["schoolid"],
name: json["name"],
logo: json["logo"],
address: json["address"],
contact: json["contact"],
principalname: json["principalname"],
principalcontact: json["principalcontact"],
slogan: json["slogan"],
webAddress: json["web_address"] == null ? null : json["web_address"],
description: json["description"] == null ? null : json["description"],
email: json["email"],
pan: json["pan"],
establishedYear: json["established_year"],
);
Map<String, dynamic> toJson() => {
"schoolid": schoolid,
"name": name,
"logo": logo,
"address": address,
"contact": contact,
"principalname": principalname,
"principalcontact": principalcontact,
"slogan": slogan,
"web_address": webAddress == null ? null : webAddress,
"description": description == null ? null : description,
"email": email,
"pan": pan,
"established_year": establishedYear,
};
}
This is how I am trying to fetch data:
class HomePageModels with ChangeNotifier{
List<HomePageModel> _hItem = [];
List<HomePageModel> get hItem{
return [..._hItem];
}
Future<void> getHomeData(BuildContext context) async{
const url = "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try{
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
List<HomePageModel> loadedHomeData = [];
if(extractedData == null){
return;
}
if(response.statusCode == 200){
print(extractedData);
}
extractedData.forEach((element){
loadedHomeData.add(HomePageModel.fromJson(element));
});
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
}catch(e){
rethrow;
}
}
}
But I am getting error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
The problem is the way you are trying to parse the data, you don't need to loop over every element to parse it, in your model just make it return a list type like this,
class HomePageModel with ChangeNotifier {
List<Datum>? data;
HomePageModel({this.data});
HomePageModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Datum>[];
json['data'].forEach((v) {
data!.add(new Datum.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
Datum.fromJson(Map<String, dynamic> json) {
schoolid = json["schoolid"];
name = json["name"];
logo = json["logo"];
address = json["address"];
contact = json["contact"];
principalname = json["principalname"];
principalcontact = json["principalcontact"];
slogan = json["slogan"];
webAddress = json["web_address"];
description = json["description"];
email = json["email"];
pan = json["pan"];
establishedYear = json["established_year"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['schoolid'] = this.schoolid;
data['name'] = this.name;
data['logo'] = this.logo;
data['address'] = this.address;
data['contact'] = this.contact;
data['principalname'] = this.principalname;
data['principalcontact'] = this.principalcontact;
data['slogan'] = this.slogan;
data['web_address'] = this.webAddress;
data['description'] = this.description;
data['email'] = this.email;
data['pan'] = this.pan;
data['established_year'] = this.establishedYear;
return data;
}
}
and in your view model you can just parse the extracted data from response.body like this,
class HomePageModels with ChangeNotifier {
HomePageModel? _hItem;
HomePageModel get hItem {
return _hItem!;
}
Future<void> getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-
4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
if (extractedData == null) {
return;
}
if (response.statusCode == 200) {
print(extractedData);
}
HomePageModel loadedHomeData =
HomePageModel.fromJson(extractedData);
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
} catch (e) {
rethrow;
}
}
}
getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final extractedData = json.decode(response.body);
List loadedHomeData = extractedData;
_hItem = loadedHomeData.map((e) => HomePageModel.fromJson(e)).toList();
}
notifyListeners();
return _hItem;
} catch (e) {
rethrow;
}
}

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.

I am getting null value of user_id

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