flutter Error: The method '[]' was called on null. Receiver: null Tried calling: []("product")
2,562
According to the error your cartCardApi is null before you are accessing it in the ListView.
If it'a is an API call use FutureBuilder to handle all the asynchronous calls like showing loading, error when there is an error from api and the ui if its success.
Otherwise make cartCardApi as an empty list from before.
So that when you call setState the new list is updated and ui gets the new list.
Author by
Deepak
Updated on December 30, 2022Comments
-
Deepak over 1 year
when I clicking on my cart icon then open my cartpage.dart in this page my data not showing and give error but when i am using fast reload flutter page then that data is comming. How to solve it please help me.
error=> The method '[]' was called on null. Receiver: null Tried calling:
This is my cartPage.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:hospital/CartPage/components/cartCard.dart'; import 'package:hospital/CartPage/components/priceDetailsCard.dart'; import 'package:hospital/constant.dart'; import 'package:hospital/customApiVariable.dart'; import 'package:http/http.dart' as http; class Cartpage extends StatefulWidget { @override _CartpageState createState() => _CartpageState(); } class _CartpageState extends State<Cartpage> { var response; var addToCartApi; @override void initState() { super.initState(); fetchData(); } fetchData() async { var api = Uri.parse( '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${var_uid}'); response = await http.get(api); print("Carousel" + response.body); addToCartApi = jsonDecode(response.body); print('addToCartApi' + addToCartApi['total'].toString()); // store in variable totalOfferPrice = addToCartApi['total']['grandTotalOfferPrice'].toString(); totalPrice = addToCartApi['total']['grandTotalPrice'].toString(); totalPriceAfterOffer = addToCartApi['total']['grandTotalPriceAfterOffer'].toString(); deliveryName = addToCartApi['total']['deliveryName']; deliveryCharge = addToCartApi['total']['deliveryCharge'].toString(); total_num = addToCartApi['total']['num'].toString(); setState(() {}); } // List allItems = CartRepo().getAllCartItems(); @override Widget build(BuildContext context) { final _media = MediaQuery.of(context).size; return Scaffold( appBar: AppBar( backgroundColor: kGreen, title: Text("My Cart"), ), body: Stack( children: [ Container( decoration: BoxDecoration(color: Color(0xFFeeeeee)), height: _media.height, width: _media.width, ), ListView( shrinkWrap: true, children: <Widget>[ CartCard(user_id: var_uid), PriceDetailsCard(totalItem: addToCartApi['total']), SizedBox( height: 100, ) ], ), Align( alignment: Alignment.bottomCenter, child: Container( width: _media.width, height: _media.height * .08, decoration: BoxDecoration(color: Colors.white, boxShadow: [ BoxShadow(color: Colors.black87, blurRadius: 5.0), BoxShadow(color: Colors.white, blurRadius: 10.0), ]), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "\u20B9 ${totalPriceAfterOffer}", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20), ), Text( "View price details", style: TextStyle( color: Colors.blueGrey, fontWeight: FontWeight.bold), ) ], ), ), Padding( padding: const EdgeInsets.only(right: 10.0), child: Container( width: _media.width * .4, child: RaisedButton( onPressed: () {}, color: kGreen, child: Text( "PLACE ORDER", style: TextStyle(color: Colors.white), ), )), ), ], ), ), ) ], )); } }
This is CartCard.dart page
import 'dart:convert'; import 'package:flutter/material.dart'; // import 'package:hospital/FourthDelete/fourth_delete.dart'; // import 'package:hospital/FourthSection/MedicineProductList/medicine_product_list.dart'; import 'package:hospital/ProductDetailsPage/product_detailPage.dart'; import 'package:hospital/SecondSection/Medicine/medicine_page.dart'; import 'package:hospital/constant.dart'; import 'package:hospital/customApiVariable.dart'; import 'package:http/http.dart' as http; class CartCard extends StatefulWidget { final user_id; const CartCard({Key key, this.user_id}) : super(key: key); @override _CartCardState createState() => _CartCardState(); } class _CartCardState extends State<CartCard> { var response; //this drinks call from api var cartCardApi; @override void initState() { // TODO: implement initState // super.initState(); // for loading fetchData(widget.user_id); } fetchData(auth_uid) async { // var api = Uri.parse( // 'https://www.a2rstore.in/oceonicApi/ecommerce/v2/api/categoryApi.php?a2rTokenKey=carpet1234'); // var api = Uri.parse('$baseUrl/productCatApi.php?a2rTokenKey=$a2rTokenKey'); var api = Uri.parse( // '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${widget.auth_uid}'); '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${widget.user_id}'); // 'https://www.a2rstore.in/oceonicApi/ecommerce/v1/api/productSubCatApi.php?a2rTokenKey=a2rhos1234&pcat=60c461f032f2a'); response = await http.get( api, ); print("cartCardApi " + api.toString()); print("cartCardbody " + response.body); // in double quotes drink is key value of json cartCardApi = jsonDecode(response.body); print("cartCardApi " + cartCardApi.toString()); return cartCardApi['product']; // setState(() {}); } String quantity = "1"; @override Widget build(BuildContext context) { final _media = MediaQuery.of(context).size; return ListView.builder( // itemCount: categoryApi.length.clamp(0, 3),//THis is for showed minimun length of item listview.builder flutter itemCount: cartCardApi['product'].length, scrollDirection: Axis.vertical, physics: ScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) { var cartCard = cartCardApi['product'][index]; return Container( height: _media.height * .4, child: Card( color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only( left: 10.0, top: 10, bottom: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( width: _media.width * .6, child: Text( // widget.item.desc, cartCard["productName"], maxLines: 2, style: TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis, ), ), SizedBox( height: 5, ), Text( // widget.item.quantity, ' Quantity ${cartCard['orderQuantity']}', style: TextStyle(color: Colors.grey, fontSize: 14), ), SizedBox( height: 10, ), Row( children: <Widget>[ Text( "Seller: ", style: TextStyle( color: Colors.grey, fontSize: 14), ), Icon( Icons.check_circle, color: Colors.grey, size: 15, ) ], ), SizedBox( height: 15, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Text( "\u20B9 " + cartCard[ 'productPriceAfterOffer'], style: TextStyle( fontWeight: FontWeight.bold, fontSize: 23), ), Padding( padding: const EdgeInsets.only(left: 10.0), child: Text( "\u20B9 " + cartCard['productRealPrice'], style: TextStyle( color: Colors.grey, decoration: TextDecoration.lineThrough), ), ), SizedBox( width: 5, ), Text( '40' + "%off", style: TextStyle( color: Colors.green, fontSize: 13, fontWeight: FontWeight.w600), ) ], ), SizedBox( height: 10, ), Text( "2 offers available", style: TextStyle( color: Colors.green, fontSize: 13, fontWeight: FontWeight.w600), ) ], ) ], ) ], ), ), Padding( padding: const EdgeInsets.only( top: 10.0, right: 8, bottom: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( color: Colors.white, child: Row( children: <Widget>[ Container( width: _media.width * .3, height: _media.height * .2, child: Image.network( // 'https://media.gettyimages.com/photos/woman-using-meal-delivery-service-through-mobile-app-picture-id1160735344?k=6&m=1160735344&s=612x612&w=0&h=tYEeckvNDyAoyUEfUeCii_29p_pBum_BVHKiUrGbjYY=', cartCard['pImgImg'], fit: BoxFit.cover, ), ) ], ), ), Row( children: <Widget>[ Text( "Qty:", style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox( width: 10, ), DropdownButton<String>( value: quantity, items: <String>["1", "2", "3", "4", "5"] .map((String value) => DropdownMenuItem<String>( value: value, child: Text(value))) .toList(), onChanged: (_value) { setState(() { quantity = _value; }); }, ) ], ), ], ), ) ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( height: _media.height * .08, width: _media.width * .4875, child: RaisedButton( onPressed: () {}, color: Colors.white, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( Icons.favorite, size: 15, color: Colors.grey, ), SizedBox( width: 5, ), Text( "SAVE FOR LATER", style: TextStyle(fontSize: 15), ) ], ), ), ), Container( height: _media.height * .08, width: _media.width * .4875, child: RaisedButton( onPressed: () {}, color: Colors.white, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( Icons.delete, size: 15, color: Colors.grey, ), SizedBox( width: 5, ), Text( "REMOVE", style: TextStyle(fontSize: 15), ) ], ), ), ), ], ) ], ), ), ); }); } }
This is my json data
{ "product": [ { "plistId": "60c71ed46839f", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "1", "date": "2021-07-06", "productName": "MUKTI CHURNA", "productCode": "499", "productlink": "detail.php?pListName=MUKTI CHURNA&plistId=60c71ed46839f", "productRealPrice": "1112", "productPriceAfterOffer": 1110, "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Mukti-Churan-600x600.jpg", "subTotalRealPrice": 1110, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 1110 }, { "plistId": "60cacee2ee4ff", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "1", "date": "2021-07-06", "productName": " PAIN CALM OIL", "productCode": "504", "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff", "productRealPrice": "123", "productPriceAfterOffer": "123", "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg", "subTotalRealPrice": 123, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 123 }, { "plistId": "60cacee2ee4ff", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "3", "date": "2021-07-06", "productName": " PAIN CALM OIL", "productCode": "504", "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff", "productRealPrice": "123", "productPriceAfterOffer": "123", "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg", "subTotalRealPrice": 369, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 369 }, { "plistId": "60cacee2ee4ff", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "3", "date": "2021-07-06", "productName": " PAIN CALM OIL", "productCode": "504", "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff", "productRealPrice": "123", "productPriceAfterOffer": "123", "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg", "subTotalRealPrice": 369, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 369 }, { "plistId": "60cacee2ee4ff", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "1", "date": "2021-07-06", "productName": " PAIN CALM OIL", "productCode": "504", "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff", "productRealPrice": "123", "productPriceAfterOffer": "123", "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg", "subTotalRealPrice": 123, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 123 }, { "plistId": "60cacee2ee4ff", "plistPriceId": "", "uid": "60daaedd3b9f8751161", "orderQuantity": "1", "date": "2021-07-06", "productName": " PAIN CALM OIL", "productCode": "504", "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff", "productRealPrice": "123", "productPriceAfterOffer": "123", "productOfferAmountMulOrdrQuantity": 0, "quantity": "1 p", "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg", "subTotalRealPrice": 123, "subTotalofferPrice": 0, "subTotalPriceAfterOffer": 123 } ], "total": { "grandTotalOfferPrice": 0, "grandTotalPrice": 123, "grandTotalPriceAfterOffer": 123, "deliveryName": "Shipping Charge", "deliveryCharge": "Free", "num": 6 } }
-
Earthling over 1 yearHi deepak. Have you ben able to solve the above ? I have a similar issue : stackoverflow.com/questions/74284254/…
-
-
Deepak almost 3 yearsI added my json data please check once again
-
Deepak almost 3 yearsI added my json data please check once again.
-
Deepak almost 3 yearsI added my json data please check once again.
-
Pradyot Prakash almost 3 yearsissue is not with the json data. issue is in CartCard widget. in the state you have cartCardApi variable. declare it like var cartCardApi = []; this might fix the problem. but I think the better approach would be to use FutureBuilder.
-
Deepak almost 3 yearsI used FutureBuilder then i got this error type 'String' is not a subtype of type 'int' of 'index' on FutureBuilder
-
sujith sa almost 3 yearswhat output are you getting on your print("cartCardApi " + cartCardApi.toString());
-
Earthling over 1 yearHi Pradyot. I have a similar issue. Can you help me out ?: stackoverflow.com/questions/74284254/…
-
Earthling over 1 yearHi sujith.I have a similar issue.Can you help ? : stackoverflow.com/questions/74284254/…