首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在遍历一个对象数组时遇到了困难。

我在遍历一个对象数组时遇到了困难。
EN

Stack Overflow用户
提问于 2021-09-27 11:27:42
回答 1查看 127关注 0票数 0

我正在尝试遍历一个对象数组,我将它们存储在我的SharedPreferences中,在这里我从firebase中获取数据并为每个对象添加数量,现在我只想在购物车中显示产品的标题、价格和数量。我能够将属于产品的所有值都拉到购物车屏幕上,但是如何循环遍历购物车屏幕中的嵌套值是个问题。还有人能帮我了解更多关于颤振的知识吗?

代码语言:javascript
复制
Cart screen
@override
  Widget build(BuildContext context) {
    SharedPreferences prefs = SharedPreferences.getInstance() as SharedPreferences;
    var cart = prefs.getStringList('userCart');
    return Row(
      children: [
        SizedBox(
          width: getProportionateScreenWidth(88),
          child: AspectRatio(
            aspectRatio: 0.88,
            child: Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Color(0XFFF5F6F9),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Image.network(cart![0]),
              // child: Image.network(cart.product.images[0]),
            ),
          ),
        ),
        SizedBox(
          width: getProportionateScreenWidth(20),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              cart.first,
              // cart.product.title,
              style: TextStyle(fontSize: 16, color: Colors.black),
              maxLines: 2,
            ),
            const SizedBox(
              height: 10,
            ),
            Text.rich(
              TextSpan(
                text: "\$${cart.product.price}",
                style: TextStyle(
                  color: kPrimaryColor,
                ),
                children: [
                  TextSpan(
                    text: " x${cart.numOfItem}",
                    style: TextStyle(
                      color: kTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  }
代码语言:javascript
复制
Storing the data from firebase and adding quantity 
Future<void> checkItemInCart(
    Product product, int quantity, BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // convert to map
  var product_str = product.toMap();

  // combine product with quantity
  String productWithQuantity =
      product_str.toString() + '-quantity-' + quantity.toString();

  // check if project exists first
  List<String> userCartPref = (prefs.getStringList('userCart') ?? <String>[]);
  ['Product-quantity-2'];

  /*
   update {
   check if found
   }
  */

  List<String> temp = (prefs.getStringList('userCart') ?? <String>[]);
  // add f
  //userCartPref ['iphone 1','laptop 3'];
  // temp ['laptop 3'];
  var foundInCart = false;
  for (var i = 0; i < userCartPref.length; i++) {
    var item = userCartPref[i];
    var items = item.split('-quantity-'); //list [product,quantity]
    var old_product = items[0];
    var old_qty = items[1];
    if (old_product.contains(product.pid)) {
      foundInCart = true;
      // product exists
      // delete the current item
      temp.removeAt(i);
      // set pref to temp
      prefs.setStringList('userCart', temp);

      // sum the quantity 2 1
      String finalQuantity = (quantity + int.parse(old_qty)).toString();
      // create string for pref with the updated quantity
      String updatedProductWithQuantity =
          product_str.toString() + '-quantity-' + finalQuantity;
      //add item with the updated quantity iphone 2
      addItemToCart(updatedProductWithQuantity, context);
      showSnackBar(context, "Quantity has been updated successfully");

      break;
    }

  
  }
  if (userCartPref.length == 0 || foundInCart == false) {
    addItemToCart(productWithQuantity, context);
    showSnackBar(context, "Product added successfully to cart");
  }

  await getProducts();
}
代码语言:javascript
复制
Future<void> addItemToCart(String product, BuildContext context) async {
  // await clearPref();
  print("inside");
  SharedPreferences prefs = await SharedPreferences.getInstance();
  List<String> tempCartList = (prefs.getStringList('userCart') ?? <String>[]);
  // print(tempCartList);
  tempCartList.add(product);
  prefs.setStringList('userCart', tempCartList);
}
代码语言:javascript
复制
Future<void> getProducts() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  List<String> tempCartList =
      (preferences.getStringList('userCart') ?? <String>[]);
  for (var i = 0; i < tempCartList.length; i++) {
    var item = tempCartList[i];
    var items = item.split('-quantity-');
    var product_ = items[0];
    var quantity_ = items[1];
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-27 11:48:07

您可以使用ListView.builder或GridView.builder迭代数组并在屏幕上呈现它们。因此,如果我使用ListView.builder,cart screen中的代码如下所示:

代码语言:javascript
复制
return ListView.builder(
  itemCount: cart.length, //length of cart
  itemBuilder: (context, index) {
    return Row(
      children: [
        SizedBox(
          width: getProportionateScreenWidth(88),
          child: AspectRatio(
            aspectRatio: 0.88,
            child: Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Color(0XFFF5F6F9),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Image.network(cart![index]),
              // child: Image.network(cart.product.images[0]),
            ),
          ),
        ),
        SizedBox(
          width: getProportionateScreenWidth(20),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              cart[index].product.title,
              // cart.product.title,
              style: TextStyle(fontSize: 16, color: Colors.black),
              maxLines: 2,
            ),
            const SizedBox(
              height: 10,
            ),
            Text.rich(
              TextSpan(
                text: "\$${cart[index].product.price}",
                style: TextStyle(
                  color: kPrimaryColor,
                ),
                children: [
                  TextSpan(
                    text: " x${cart[index].numOfItem}",
                    style: TextStyle(
                      color: kTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  },
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69345796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档