i can’t seems to find the solutions for this problem..
i cant view my cartlist, saying the type ‘Null’ is not a subtype of type ‘String’.
class Cart {
int? cart_id;
int? user_id;
int? item_id;
int? cart_quantity;
String? cart_color;
String? cart_size;
String? item_name;
double? item_rating;
List<String>? item_tags;
double? item_price;
List<String>? item_color;
List<String>? item_size;
String? item_desc;
String? item_image;
Cart({
this.cart_id,
this.user_id,
this.item_id,
this.cart_quantity,
this.cart_color,
this.cart_size,
this.item_name,
this.item_rating,
this.item_tags,
this.item_price,
this.item_color,
this.item_size,
this.item_image,
this.item_desc,
});
factory Cart.fromJson(Map<String, dynamic>json) => Cart (
cart_id: int.parse(json['cart_id']),
user_id: int.parse(json['user_id']),
item_id: int.parse(json['item_id']),
cart_quantity: int.parse(json['item_quantity']),
cart_size: json['cart_size'],
cart_color: json['cart_color'],
item_name: json['item_name'],
item_rating: double.parse(json['item_rating']),
item_tags: json['item_tags'].toString().split(', '),
item_price: double.parse(json['item_price']),
item_color: json['item_color'].toString().split(', '),
item_size: json['item_size'].toString().split(', '),
item_desc: json['item_desc'],
item_image: json['item_image'],
);
}
above is my cart model
import 'package:get/get.dart';
import '../model/cart.dart';
class CartListController extends GetxController {
final RxList<Cart> _cartList = <Cart>[].obs;
final RxList<int> _selectedItemList = <int>[].obs;
final RxBool _isSelectedAll = false.obs;
final RxDouble _total = 0.0.obs;
List<Cart> get cartList => _cartList.value;
List<int> get selectedItemList => _selectedItemList.value;
bool get isSelected => _isSelectedAll.value;
double get total => _total.value;
setList(List<Cart> list) {
_cartList.value = list;
}
addSelectedItem(int itemSelectedID) {
_selectedItemList.value.add(itemSelectedID);
update();
}
deleteSelected(int itemSelectedID) {
_selectedItemList.value.remove(itemSelectedID);
update();
}
setIsSelectedAll () {
_isSelectedAll.value = !_isSelectedAll.value;
}
clearAllSelected() {
_selectedItemList.value.clear();
update();
}
setTotal (double overallTotal){
_total.value = overallTotal;
}
}
above is my cart_list controller
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:shop_app/users/model/cloth.dart';
import 'package:shop_app/users/userPreferences/current_user.dart';
import 'package:http/http.dart' as http;
import '../../api_connection/api_connection.dart';
import '../controllers/cart_list_controller.dart';
import '../model/cart.dart';
class CartListScreen extends StatefulWidget {
const CartListScreen({super.key});
@override
State<CartListScreen> createState() => _CartListScreenState();
}
class _CartListScreenState extends State<CartListScreen> {
final currentOnlineUser = Get.put(CurrentUser());
final cartListController = Get.put(CartListController());
getCurrentUserCartList () async {
List<Cart> cartListOfCurrentUser = [];
try {
var user = currentOnlineUser.user.user_id.toString();
var res = await http.post(Uri.parse(API.getCartList),
body:
{"currentOnlineUserID": user}
);
if (res.statusCode == 200)
{
var resBodyOfCurrentUserCartItems = jsonDecode(res.body);
if(resBodyOfCurrentUserCartItems["success"] == true)
{
(resBodyOfCurrentUserCartItems['currentUserCartData'] as List).forEach((eachCurrentUserCartData)
{
cartListOfCurrentUser.add(Cart.fromJson(eachCurrentUserCartData));
});
} else {
Fluttertoast.showToast(msg: "status code not 200");
print ("not 200");
}
}
else {
Fluttertoast.showToast(msg: "error occured while executing query");
}
cartListController.setList(cartListOfCurrentUser);
//print(cartListController.cartList);
}
catch (errorMsg)
{
Fluttertoast.showToast(msg: "Error:: $errorMsg");
if (kDebugMode) {
print("error 2 : $errorMsg");
}
}
calculateTotalAmount ();
}
calculateTotalAmount () {
cartListController.setTotal(0);
if(cartListController.selectedItemList.isNotEmpty)
{
for (var itemInCart in cartListController.cartList) {
if(cartListController.selectedItemList.contains(itemInCart.item_id))
{
double eachItemTotalAmount = (itemInCart.item_price!) * (double.parse(itemInCart.cart_quantity.toString()));
cartListController.setTotal(cartListController.total + eachItemTotalAmount);
}
}
}
}
@override
void initState() {
super.initState();
getCurrentUserCartList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Cart"),
),
backgroundColor: Colors.black,
body: Obx(()=>
cartListController.cartList.isNotEmpty ? ListView.builder(
itemCount: cartListController.cartList.length,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
Cart cartModel = cartListController.cartList[index];
Cloth clothModel = Cloth(
item_id: cartModel.item_id,
item_colors: cartModel.item_color,
item_name: cartModel.item_name,
item_price: cartModel.item_price,
item_image: cartModel.item_image,
item_size: cartModel.item_size,
item_rating: cartModel.item_rating,
item_tag: cartModel.item_tags,
item_desc: cartModel.item_desc
);
return SizedBox(
width: MediaQuery.of(context).size.width,
child: Row(
children: [
GetBuilder(
init: CartListController(),
builder: (c){
return IconButton(
onPressed: (){},
icon: Icon(
cartListController.selectedItemList.contains(cartModel.item_id)
? Icons.check_box : Icons.check_box_outline_blank,
//color: cartListController.setIsSelectedAll ? Colors.white : Colors.grey,
)
);
}
),
Expanded(
child: GestureDetector(
onTap: (){},
child: Container(
margin: EdgeInsets.fromLTRB(0, index == 0 ? 16 : 8, 16, index == cartListController.cartList.length - 1 ? 16 : 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.black,
boxShadow: const [
BoxShadow(
color: Colors.white,
offset: Offset(0,0),
blurRadius: 6,
),]
),
child: Row(
children: [
Expanded(
child: Padding(padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
clothModel.item_name.toString(),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 20,),
Row(
children: [
Expanded(
child: Text(
"Color: ${cartModel.cart_color!}nSize: ${cartModel.cart_size!}",
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white60,
fontWeight: FontWeight.bold,
fontSize: 14,
)),
)],
),
const SizedBox(height: 10,),
],
)
),
)
],
),
))
),],
),
);
},
) : const Center(child: CartIsEmpty(),),
),
);
}
}
class CartIsEmpty extends StatelessWidget {
const CartIsEmpty({super.key});
@override
Widget build(BuildContext context) {
return const Text("cart is empty", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 30),);
}
}
this is my cart screen
I have checked the name in the database to make sure the name is right, but i cant get it right..
i have run print debugging and seems that i stuck on this line on cart_screen
cartListOfCurrentUser.add(Cart.fromJson(eachCurrentUserCartData));
the errors is gone when i comment on it.. but i don’t get it which one is not acceptable string.
if i comment it, i can print calling eachCurrentUserCartData in this block and return data in terminal.
i needed the data for updating my listview widget
getCurrentUserCartList () async {
List<Cart> cartListOfCurrentUser = [];
try {
var user = currentOnlineUser.user.user_id.toString();
var res = await http.post(Uri.parse(API.getCartList),
body:
{"currentOnlineUserID": user}
);
if (res.statusCode == 200)
{
var resBodyOfCurrentUserCartItems = jsonDecode(res.body);
if(resBodyOfCurrentUserCartItems["success"] == true)
{
(resBodyOfCurrentUserCartItems['currentUserCartData'] as List).forEach((eachCurrentUserCartData)
{
//cartListOfCurrentUser.add(Cart.fromJson(eachCurrentUserCartData));
print(eachCurrentUserCartData);
});
} else {
Fluttertoast.showToast(msg: "status code not 200");
print ("not 200");
}
}
else {
Fluttertoast.showToast(msg: "error occured while executing query");
}
cartListController.setList(cartListOfCurrentUser);
//print(cartListController.cartList);
}
catch (errorMsg)
{
Fluttertoast.showToast(msg: "Error:: $errorMsg");
if (kDebugMode) {
print("error 2 : $errorMsg");
}
}
I’m very new to programming so very much appreciate the help. thank you!
2
Answers
change your Factory constructor to the following:
Explanation:
The parse method is expecting string value and will throw exception if it is not parse-able. so in this case if we are not sure that we will get the correct and not null able value. we will use tryParse which is taking string and will return null value if it is not parse-able.
just add null checks on ur jsonParse ….