【问题标题】:flutter Problem same quantity show on products颤振问题相同数量显示在产品上
【发布时间】:2021-09-23 02:45:22
【问题描述】:

当我增加一种产品的数量时,所有产品的数量都在增加,那么如何解决。

这是我的产品页面:

import 'dart:convert';

import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hospital/Authentication/LoginLogoutScreenPage/login.dart';
import 'package:hospital/CartPage/Cart_Api/cart_api.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/ProductDetailsPage/product_detailPage.dart';
import 'package:hospital/ProductDetailsPage/related_product_page.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;
import 'package:line_icons/line_icons.dart';
import 'package:provider/provider.dart';

class DetailPage extends StatefulWidget {
  final plistId;

  const DetailPage({Key key, this.plistId}) : super(key: key);
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  int quantity = 1;
  var response;
  var detailPageApi;

  @override
  void initState() {
    super.initState();
    fetchData(widget.plistId);
  }

  fetchData(var consultWithDoctor) async {
    var api = Uri.parse(
        '$ecommerceBaseUrl/productListApi.php?a2rTokenKey=$a2rTokenKey&plistId=${widget.plistId}');
    response = await http.get(
      api,
    );
    print("detailPageApi " + api.toString());
    print("detailPageBody " + response.body);
    detailPageApi = jsonDecode(response.body);

    print("detailPagelist " + detailPageApi.toString());

    setState(() {});
  }

  Future _submit() async {
    var errorMessage = 'Authentication Failed';
    if (successfully_add_cart_status.toString() == 'false') {
      errorMessage = 'Please try again later';
      print(errorMessage);
      _showerrorDialog(errorMessage);
    } else {
      errorMessage = 'Product Succesfully Added to Cart';
      print(errorMessage);
      _showerrorDialog(errorMessage);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: kGreen,
        title: Text(
          "Details",
          style: TextStyle(fontStyle: FontStyle.italic),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.shopping_cart),
            // onPressed: () => print("open cart"),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => Cartpage()),
              );
            },
          ),
          DropDownMenu(),
        ],
      ),
      body: Container(
        child: response != null
            ? ListView.builder(
                itemCount: detailPageApi.length.clamp(0, 1),
                scrollDirection: Axis.vertical,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  var details = detailPageApi[index];
                  if (details['num'] == 0) {
                    return Center(
                      child: CircularProgressIndicator(
                        backgroundColor: Colors.white,
                      ),
                    );
                  }
                  return Column(
                    children: <Widget>[
                      Hero(
                        tag: "1",
                        child: SizedBox(
                          height: 300.0,
                          width: 300.0,
                          child: Carousel(
                            boxFit: BoxFit.cover,
                            autoplay: false,
                            animationCurve: Curves.fastOutSlowIn,
                            animationDuration: Duration(milliseconds: 800),
                            dotSize: 6.0,
                            dotIncreasedColor: Colors.black,
                            dotBgColor: Colors.transparent,
                            // dotPosition: DotPosition.topRight,
                            dotVerticalPadding: 10.0,
                            showIndicator: true,
                            indicatorBgPadding: 7.0,
                            images: [
                              NetworkImage(details['pImgImg']),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 50,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Name :",
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 1.5,
                                  fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Flexible(
                              child: Text(
                                // widget.details,
                                details['productName'],
                                style: TextStyle(
                                    fontSize: 17,
                                    height: 1.5,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Details :",
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 1.5,
                                  fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Flexible(
                              child: Text(
                                // widget.details,
                                details['productDescription'],
                                style: TextStyle(
                                    fontSize: 17,
                                    height: 1.5,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          children: <Widget>[
                            Text(
                              "Price :",
                              style: TextStyle(
                                  fontSize: 18, fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  // "Rs " + widget.pPromotionPrice,
                                  "Rs 55.0",
                                  style: TextStyle(
                                      fontSize: 17,
                                      fontWeight: FontWeight.w500),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Text(
                                  // "Rs " + widget.pPrice,
                                  "Rs 100",
                                  style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500,
                                      // color: warning,
                                      decoration: TextDecoration.lineThrough),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(right: 20, left: 20),
                        child: Row(
                          children: <Widget>[
                            Text(
                              "Qty :",
                              style: TextStyle(
                                  fontSize: 17, fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Row(
                              children: <Widget>[
                                InkWell(
                                  onTap: () {
                                    if (quantity > 1) {
                                      setState(() {
                                        quantity = --quantity;
                                      });
                                    }

                                    // minus here
                                  },
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      LineIcons.minus,
                                      size: 15,
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                Text(
                                  quantity.toString(),
                                  style: TextStyle(fontSize: 16),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                InkWell(
                                  onTap: () {
                                    setState(() {
                                      quantity = ++quantity;
                                    });
                                    // minus here
                                  },
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      LineIcons.plus,
                                      size: 15,
                                    ),
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 50,
                      ),
                      InkWell(
                        onTap: () async {
                          if (var_uid.toString() != null.toString()) {
                           
                            _submit();
                            var qty = quantity.toString();
                            var plistId = widget.plistId;
                            print('pplistid' + plistId);

                            var uid = var_uid.toString();
                            var sid = var_sid.toString();
                            print('uuid' + uid);
                            print('ssid' + sid);

                            var response =
                                await add_to_cart_fn(qty, plistId, uid, sid);

                            print("rsp: " + response['msg']);
                          } else {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => LoginPage()));
                          }
                        },
                        // },
                        child: Padding(
                          padding: EdgeInsets.only(left: 20, right: 20),
                          child: Container(
                            height: 45,
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: kGreen,
                                borderRadius: BorderRadius.circular(30)),
                            child: Center(
                              child: Text(
                                "ADD TO CART",
                                style: TextStyle(
                                  color: kWhite,
                                  fontSize: 20,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 20.0),
                      RelatedProductPage(plistId: widget.plistId)
                    ],
                  );
                })
            : Center(
                child: CircularProgressIndicator(
                  backgroundColor: Colors.white,
                ),
              ),
      ),
    );
  }

  void _showerrorDialog(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey[350],
        textColor: Colors.black,
        fontSize: 16.0);
  }
}

【问题讨论】:

标签: flutter dart flutter-layout flutter-dependencies flutter-test


【解决方案1】:

@Deepak 如果您不了解地图,请改用列表,并为每个索引更新一个值。用一些大值(如 1000000)初始化一个 int 类型列表,并更新每个索引的值。使用 ListView builder 从 API 获取每个索引的数据。

List<int> quantity = List.empty(growable: true);

OR

List<int> quantity = List.filled(10000, []);

For updating quantity:-

quantity[index] += 1;

对于网格视图,请参考 CodeGrepper 中的这个示例:-

 GridView.count(
  // Create a grid with 2 columns. If you change the scrollDirection to
  // horizontal, this produces 2 rows.
  crossAxisCount: 2,
  // Generate 100 widgets that display their index in the List.
  children: List.generate(100, (index) {
    return Center(
      child: Text(
        'Item $index',
        style: Theme.of(context).textTheme.headline5,
      ),
    );
  }),
);

【讨论】:

  • 我的 productId 来自 api。这是 trendingProduct['plistId'] 用于 productId 和 ,60daba196f320 这是我的 trendingProduct['plistId' 的输出,并且在单击加号或减号按钮后得到错误类型字符串不是 int 的子类型。并且还显示 null 在哪里是 6
  • 数量[trendingProduct['plistId']] += 1;像这样我用 where are your quantity['$productId'] += 1;
  • @Deepak 您的 API 必须获取您可以使用 Listview Builder 显示的产品列表。在这种情况下,它将类似于数量[索引] +=1;。我已经更新了答案。此外,您在某处遇到类型异常。
  • 使用listview builder后如何在listview builder中使用gridview,我的用户界面会受到干扰
  • @Deepak 我已经用一个例子更新了答案
【解决方案2】:

您在所有产品中设置了共同数量,因此将其更改并设置在类中。

请检查示例

import 'package:flutter/material.dart';

class QuantityUpdatePage extends StatefulWidget {
  @override
  _QuantityUpdatePageState createState() => _QuantityUpdatePageState();
}

class _QuantityUpdatePageState extends State<QuantityUpdatePage> {
  List<Product> productArray = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      productArray.clear();
      productArray.add(Product(1, "Product 1", 1));
      productArray.add(Product(2, "Product 2", 1));
      productArray.add(Product(3, "Product 3", 1));
      productArray.add(Product(4, "Product 4", 1));
      productArray.add(Product(5, "Product 5", 1));
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("QUANTITY UPDATE")),
        body: ListView.builder(
            shrinkWrap: true,
            itemCount: productArray.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: const EdgeInsets.only(right: 20, left: 20),
                child: ListView(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                    SizedBox(
                      height: 20,
                    ),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(productArray[index].productName),
                        SizedBox(
                          width: 40,
                        ),
                        Row(
                          children: <Widget>[
                            Text(
                              "Qty :",
                              style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Row(
                              children: <Widget>[
                                InkWell(
                                  onTap: () {
                                    if (productArray[index].quantity > 1) {
                                      setState(() {
                                        productArray[index].quantity = --productArray[index].quantity;
                                      });
                                    }

                                    // minus here
                                  },
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      Icons.minimize,
                                      size: 15,
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                Text(
                                  productArray[index].quantity.toString(),
                                  style: TextStyle(fontSize: 16),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                InkWell(
                                  onTap: () {
                                    setState(() {
                                      productArray[index].quantity = ++productArray[index].quantity;
                                    });
                                    // minus here
                                  },
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      Icons.add,
                                      size: 15,
                                    ),
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 20,
                    ),
                  ],
                ),
              );
            }));
  }
}

class Product {
  String productName;
  int quantity;
  int id;

  Product(this.id, this.productName, this.quantity);
}

【讨论】:

    【解决方案3】:

    您对每个项目使用相同的 quantity 变量。更改其中之一的值将导致所有项目更新。您需要做的是根据产品 ID 选择数量的 Map。这样,每当您增加或减少数量时,您都会根据该特定产品 ID 更新数量,其余部分将保持不变。

    编辑:这是如何工作的

    //Create a new map to save the product id and product selected quantity
    var productQuantity = new Map<int, int>()
    
    //When setting the values of the product, set the quantity from the map
    Padding(
      padding: const EdgeInsets.only(right: 20, left: 20),
      child: Row(
        children: <Widget>[
          Text(
            "Qty :",
            style: TextStyle(
              fontSize: 17, fontWeight: FontWeight.w500),
            ),
            SizedBox(width: 20,),
            Row(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    if (quantity > 1) {
                      setState(() {
                        //Changed here
                        productQuantity['$productId'] -= 1;
                      });
                    }
                  },
                  child: Container(
                    width: 25,
                    height: 25,
                    decoration: BoxDecoration(shape: BoxShape.circle),
                    child: Icon(
                      LineIcons.minus,
                      size: 15,
                    ),
                  ),
                ),
                SizedBox(width: 15,),
                Text(
                  //Changed here
                  productQuantity['$productId'].toString(),
                  style: TextStyle(fontSize: 16),
                ),
                SizedBox(width: 15,),
                InkWell(
                  onTap: () {
                    setState(() {
                      //Changed here
                      productQuantity['$productId'] += 1;
                    });
                  },
                  child: Container(
                    width: 25,
                    height: 25,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle),
                    ),
                    child: Icon(
                      LineIcons.plus,
                      size: 15,
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      )
    

    【讨论】:

    • 我不明白如何使用 Map for This。
    • 我的 productId 来自 api。这是 trendingProduct['plistId'] 用于 productId 和 ,60daba196f320 这是我的 trendingProduct['plistId' 的输出,并且在单击加号或减号按钮后得到错误类型字符串不是 int 的子类型。并且还显示 null 在哪里是 6
    • productQuantity[trendingProduct['plistId']] += 1;像这样我用 where are your productQuantity['$productId'] += 1;
    • 如果您的产品 id 是字符串,则更改地图以处理它
    • 此外,当您获取所有数据时,请确保使用每个产品 id 的默认 0 值初始化地图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2021-05-09
    • 2021-07-25
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多