“getter length was called on null”显示仅在一台移动设备上按下按钮时

时间:2021-02-27 04:48:43

标签: flutter dart

*当在代码底部按下添加到购物车按钮时,控制台中会显示一个错误,表明在 null 上调用了 getter 长度。但问题仅存在于单个设备上。我已经在另外 2 台设备上进行了测试。它工作得很好。有没有人对这个问题有任何解决方案?谢谢

类 PrdDetailPage 扩展 StatefulWidget { 最终字符串 PrdID;

  const PrdDetailPage({Key key, this.PrdID}) : super(key: key);
  @override
  _PrdDetailPageState createState() => _PrdDetailPageState(PrdID);
}

class _PrdDetailPageState extends State<PrdDetailPage> {
  String _SubCatdropDownValue;

  String PrdID;
  int _n = 0;
  var arrProducts = [];
  List arrVarients = List();
  var arrImages = [];
  var arrProductImages = [];
  var ImageList = [];
  var strName = "";
  var strNos = "";
  var thumbnailImage = "";
  var varientID = "";
  var itemCount = 1;
  var strMalaName = "";
  var strItemQty = "";
  var strDescription = "";
  var strMRP = "";
  var strSellerID = "";
  var strOLD = "";
  var isLoading = true;

  _PrdDetailPageState(this.PrdID);

  @override
  void initState() {
    super.initState();
    this.ProductDetails();
    setState(() {});
  }

  Future<String> ProductDetails() async {
    String url = "https://www.clickxpress.in/admin/api/singleproducts";
    var rsp = await http.post(Uri.encodeFull(url),
        body: (<String, String>{'product_id': PrdID}));
    setState(() {
      Map<String, dynamic> map = json.decode(rsp.body);
      List<dynamic> Data = map["singleproducts"];
      arrProducts = Data;
      List<dynamic> ImageData = map["sliderimages"];
      List<dynamic> varient = map["varients"];
      arrVarients = varient;
      ImageList = ImageData;
      thumbnailImage = arrProducts[0]["thumbnail_image_url"];
      strName = arrProducts[0]["product_name"];
      strItemQty = arrProducts[0]["int_item_qty"];
      strNos = arrProducts[0]["uom"];
      strMalaName = arrProducts[0]["product_name_malayalam"];
      strDescription = arrProducts[0]["product_description"];
      strMRP = arrProducts[0]["product_selling_price"].toString();
      strOLD = arrProducts[0]["product_old_price"].toString();
      strSellerID = arrProducts[0]["seller_id"].toString();
      print("arrProducts");
      print(arrProducts);
      print("arrProducts");

      if (ImageData != null) {
        for (var value in ImageData) {
          final image = value["image_url"];
          arrProductImages.add(NetworkImage(imgUrl + image));
        }
      }
    });
    setState(() {
      isLoading = false;
    });
    return "Success";
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              width: 30,
              height: 30,
              child: Image.asset(
                'assets/images/back.png',
                colorBlendMode: BlendMode.color,
                scale: 2,
              ),
            ),
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: isLoading == true
            ? Center(
                child: CircularProgressIndicator(),
              )
            : SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [
                    Container(
                      height: 250,
                      width: double.infinity,
                      child: ImageList.isEmpty
                          ? Image(
                              image: NetworkImage(imgUrl +
                                  arrProducts[0]["thumbnail_image_url"]))
                          : Carousel(
                              images: arrProductImages.length != 0
                                  ? arrProductImages
                                  : [AssetImage("assets/images/loading.gif")],
                              autoplay: true,
                              dotSize: 3,
                              dotSpacing: 15.0,
                              dotColor: Colors.purple,
                              indicatorBgPadding: 5.0,
                              dotBgColor: Colors.black54.withOpacity(0.0),
                              moveIndicatorFromBottom: 180.0,
                              noRadiusForIndicator: true,
                            ),
                    ),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(left: 10, top: 10, right: 10),
                      alignment: Alignment.topLeft,
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  strName.toString(),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: 23,
                                      fontFamily: 'Poppins-Medium'),
                                ),
                                strItemQty == null
                                    ? Opacity(
                                        opacity: 0,
                                      )
                                    : Text("  (" +
                                        strItemQty +
                                        strNos.toString() +
                                        ")"),
                                strMalaName == null
                                    ? Opacity(
                                        opacity: 0.0,
                                      )
                                    : Text(strMalaName.toString(),
                                        style: TextStyle(
                                          fontSize: 20,
                                          fontFamily: 'Poppins-Medium',
                                        ))
                              ],
                            ),
                          ),
                          // Spacer(),
                          Row(
                            children: [
                              FavoriteButton(
                                isFavorite: true,
                                iconSize: 30,
                                valueChanged: (_isFavorite) {
                                  print('Is Favorite : $_isFavorite');
                                },
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 10, right: 10),
                      width: double.infinity,
                      child: Row(
                        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          arrVarients.length != 0
                              ? Container(
                                  decoration: BoxDecoration(
                                      border: Border.all(color: Colors.black26),
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(05)),
                                  height: 30,
                                  child: Padding(
                                      padding: const EdgeInsets.all(3),
                                      child: DropdownButton<String>(
                                        icon:
                                            Icon(Icons.arrow_drop_down_rounded),
                                        underline: SizedBox(),
                                        hint: _SubCatdropDownValue == null
                                            ? Text(
                                                arrVarients[0]['varient_title']
                                                    .toString(),
                                                style: TextStyle(fontSize: 15),
                                              )
                                            : Text(_SubCatdropDownValue),
                                        items: arrVarients.map((item) {
                                          return new DropdownMenuItem<String>(
                                            onTap: () {
                                              setState(() {
                                                varientID =
                                                    item["id"].toString();
                                                strMRP =
                                                    item['varient_new_price']
                                                        .toString();
                                                strOLD =
                                                    item['varient_old_price']
                                                        .toString();
                                                print(varientID);
                                              });
                                            },
                                            value: item['available_varients']
                                                .toString(),
                                            child: new Text(
                                                item['available_varients']
                                                    .toString()),
                                          );
                                        }).toList(),
                                        onChanged: (String newValue) {
                                          setState(() {
                                            _SubCatdropDownValue = newValue;
                                          });
                                        },
                                      )),
                                )
                              : Opacity(
                                  opacity: 0.0,
                                ),
                          SizedBox(
                            width: 10,
                          ),
                          Column(
                            children: [
                              Text(
                                rs + strMRP,
                                style: TextStyle(
                                    color: Colors.green,
                                    fontSize: 28,
                                    fontWeight: FontWeight.w700),
                              )
                            ],
                          ),
                          SizedBox(
                            width: 5,
                          ),
                          // Spacer(),
                          Text(
                            rs + strOLD,
                            style: TextStyle(
                                color: Colors.black54,
                                fontSize: 15,
                                decoration: TextDecoration.lineThrough),
                          ),
                          SizedBox(
                            width: 10,
                          ),
                          Text(
                              (100 -
                                          ((int.parse(arrProducts[0][
                                                          "product_selling_price"]
                                                      .toString()) /
                                                  int.parse(arrProducts[0]
                                                          ["product_old_price"]
                                                      .toString())) *
                                              100))
                                      .round()
                                      .toString() +
                                  "% off",
                              style:
                                  TextStyle(color: Colors.green, fontSize: 12)),
                        ],
                      ),
                    ),
                    Divider(
                      thickness: 1,
                      color: Colors.grey[200],
                      endIndent: 20,
                      indent: 20,
                    ),
                    strDescription == null
                        ? Opacity(
                            opacity: 0.0,
                          )
                        : Container(
                            margin: EdgeInsets.all(10),
                            width: double.infinity,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "Details",
                                  style: TextStyle(
                                      fontSize: 20, color: Colors.black54),
                                ),
                                SizedBox(
                                  height: 5,
                                ),
                                Text(
                                  strDescription.toString(),
                                  style: TextStyle(
                                    color: Colors.black87,
                                    fontFamily: 'Poppins-Medium',
                                    fontSize: 13,
                                  ),
                                ),
                                Divider(),
                              ],
                            ),
                          ),
                    SizedBox(
                      height: 10,
                    ),
                  ],
                ),
              ),
        bottomNavigationBar: Container(
          margin: EdgeInsets.only(
            left: 10,
          ),
          height: 50,
          width: double.infinity,
          child: Row(
            children: [
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    SizedBox(
                      height: 30,
                      width: 30,
                      child: new FloatingActionButton(
                        heroTag: "btn1",
                        onPressed: () async {
                          if (itemCount >= 2) {
                            setState(() => itemCount--);
                          }
                        },
                        child: new Icon(
                          Icons.remove,
                          color: Colors.black,
                          size: 20,
                        ),
                        backgroundColor: Colors.white,
                      ),
                    ),
                    new Text(itemCount.toString(),
                        style: new TextStyle(
                            fontSize: 20.0, fontWeight: FontWeight.bold)),
                    SizedBox(
                      width: 30,
                      height: 30,
                      child: new FloatingActionButton(
                        heroTag: "btn2",
                        onPressed: () async {
                          setState(() => itemCount++);
                        },
                        child: new Icon(
                          Icons.add,
                          color: Colors.black,
                          size: 20,
                        ),
                        backgroundColor: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              InkWell(
                splashColor: Colors.blue,
                onTap: () async {
                  String url = "https://www.clickxpress.in/admin/api/addtocart";
                  SharedPreferences prefs =
                      await SharedPreferences.getInstance();
                  var strKey = prefs.getString('userKey');
                  print("__________CART DETAILSS______________");
                  print("sellerId" + strSellerID);
                  print("mrp" + strMRP);
                  print("PRDID" + PrdID);
                  print(strKey);
                  print("varID" + varientID);
                  print(itemCount.toString());

                  var rsp = await http.post(Uri.encodeFull(url),
                      body: (<String, String>{
                        'customer_id': strKey,
                        'product_id': PrdID,
                        "seller_id": strSellerID,
                        'product_qty': itemCount.toString(),
                        'price': strMRP,
                        'varient_id': varientID,
                      }));
                  setState(
                    () {
                      Map<String, dynamic> map = json.decode(rsp.body);
                      print(map);
                      if (map["success"] == true) {
                        Flushbar(
                          mainButton: FlatButton(
                            onPressed: () {
                              Navigator.pushReplacement(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (context) => CartScreen(
                                            PrdQty: itemCount.toString(),
                                          )));
                            },
                            child: Text(
                              "View Cart",
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          message: map["message"].toString(),
                          duration: Duration(seconds: 3),
                        )..show(context);
                      } else {
                        Flushbar(
                          message: map["message"].toString(),
                          duration: Duration(seconds: 3),
                        )..show(context);
                      }
                    },
                  );
                  setState(() {});
                },
                child: Ink(
                  height: 50,
                  width: 150,
                  decoration: BoxDecoration(
                      color: Colors.lightBlueAccent,
                      borderRadius: BorderRadius.circular(5)),
                  child: Center(
                    child: Text(
                      "Add to Cart",
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

你有这条线:

app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tvAppName"
app:layout_constraintHeight_percent="0.35"
app:layout_constraintWidth_percent="0.45"

如果 List<dynamic> varient = map["varients"]; arrVarients = varient; varient,请检查:

null