简体   繁体   English

我在遍历对象数组时遇到问题

[英]I am having trouble iterating through an array of objects

I am trying to go through an array of objects, I stored them in my SharedPreferences where I go the data from firebase and add the quantity for each object, now I only want to display the title, price, and quantity of the product in the cart.我正在尝试通过对象数组 go,我将它们存储在我的 SharedPreferences 中,其中我 go 来自 firebase 的数据并添加每个 object 的数量,现在我只想在大车。 I was able to pull all the values belonging to the product to the cart screen but how to loop through the nested values in the cart screen is the problem.我能够将属于产品的所有值都拉到购物车屏幕,但问题是如何遍历购物车屏幕中的嵌套值。 please can anyone help me still learning more on flutter?请任何人都可以帮助我在 flutter 上了解更多信息吗?

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,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  }
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();
}
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);
}
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];
  }
}

you can use ListView.builder or GridView.builder to iterate over the array and render them on screen.您可以使用 ListView.builder 或 GridView.builder 遍历数组并将它们呈现在屏幕上。 So if I use ListView.builder, my code in cart screen would look like:因此,如果我使用 ListView.builder,我在cart screen中的代码将如下所示:

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,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  },
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在加载 CatDetailHeader 时遇到问题 - I am having trouble loadding CatDetailHeader 我在渲染容器和扩展面板列表 flutter 时遇到问题 - I am having trouble rendering a container and an expanded panel list flutter 我在访问 Flutter 中的数组值时遇到问题 - I'm having trouble accessing an array value in Flutter 我在使用 Bloc/cubit 在 flutter 的其他小部件/类中使用 BlocBuilder 获取上次发出的 state 时遇到问题 - I am having trouble getting last emitted state with BlocBuilder in other widgets/classes in flutter using Bloc/cubit 我在为我的 Flutter 应用程序创建一个简单的主页时遇到问题“未实现的静态目标丢失处理” - I am having trouble Creating A simple Hompage For my Flutter app "Unimplemented handling of missing static target" 我无法从 Google Place API 自动完成获取数据 - I am having trouble getting data from Google Place API AutoComplete 我当时无法使用.map语法理解Iterable类。 你能用一种简单的语言来表达吗? - I am having trouble understanding the Iterable class then with the .map syntax. can you put this in a simple language? 遍历对象数组 - Traversing through an array of objects 我遇到了参数类型“void Function(bool)”的问题无法分配给参数类型“void Function(bool?)?” - I am having trouble with argument type 'void Function(bool)' can't be assigned to the parameter type 'void Function(bool?)?' 我如何在颤动中遍历一组对象 - How can i loop through an array of objects in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM