How to increase the value of a specific item?

Viewed 36

I am making a cart where it shows me the list of items added with the option to remove the item and a counter to increase or decrease quantity. The option to delete works correctly for me, but the on the counter when I want to increase or reduce the quantity affects all the items in the cart.

I am new to flutter and this is getting very complicated for me, I would appreciate all the comments and advice you can give me.

cart.dart

class Cart extends StatefulWidget {
  //final List<Dish> _cart;
  List<ProductsModels> _cart;

  Cart(this._cart);

  @override
  _CartState createState() => _CartState(_cart);
}

class _CartState extends State<Cart> {
  _CartState(this._cart);

  List<ProductsModels> _cart;

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

  int items = 1;
  
  double getPrice() {
    double price = 0;
    _cart.forEach((x) {
      price += double.parse(x.pricebase) * 1 * items;
    });
    return price;
  }

  int getItemss() {
    //int items = 0;
    _cart.forEach((x) {
      items++;
    });
    _cart.forEach((x) {
      items--;
    });
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(80),
        child: AppBar(
          iconTheme: IconThemeData(color: Colors.black),
          backgroundColor: Colors.white,
          elevation: 0.0,
          centerTitle: true,
          title: Image.asset(
            "assets/images/3.png",
            width: 140,
            height: 70,
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 20.0),
            ListView.builder(
              shrinkWrap: true,
                itemCount: _cart.length,
                itemBuilder: (context, index) {
                  var item = _cart[index];
                  return Padding(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                    child: Card(
                      semanticContainer: true,
                        clipBehavior: Clip.antiAliasWithSaveLayer,
                        elevation:4.0,
                      child: Container(
                        height: 110,
                        alignment: Alignment.center,
                        child: 
                        Row(
                          children: <Widget>[
                            AspectRatio(
                              aspectRatio: 1.2,
                              child: Stack(
                                children: <Widget>[
                                  Align(
                                    alignment: Alignment.bottomLeft,
                                    child: Container(
                                      height: 70,
                                      width: 70,
                                      child: Stack(
                                        children: <Widget>[
                                          Align(
                                            alignment: Alignment.bottomLeft,
                                            child: Container(
                                              decoration: BoxDecoration(
                                                  color: Colors.grey[200],
                                                  borderRadius: BorderRadius.circular(10)),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                    left: -20,
                                    //bottom: -20,
                                    child: Image.network( 'https://cdn.pixabay.com/photo/2015/02/07/20/58/tv-627876_640.jpg',width: 170,fit: BoxFit.fill, ),
                                  )
                                ],
                              ),
                            ),

                            //VIEW DE LOS ARTICULOS EN EL CARRITO
                            
                            Expanded(
                              child: 
                              ListTile(
                                title: Column(
                                  mainAxisAlignment: MainAxisAlignment.start, //center
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(item.description,),
                                    Text(item.name),
                                    SizedBox(height: 0),

                      //COUNTER DE ARTICULOS EN CARRITO
                                    Row(
                                      children: [
                                        items!=0? new IconButton(
                                          icon: new Icon(Icons.remove),
                                          onPressed: (){
                                            items--;
                                            if(items == 0){
                                              //ALERTA AL SELECCIONAR CERO ELEMENTOS DENTRO DEL CARRITO
                                              showDialog(
                                                context: context,
                                                builder: (_)=> AlertDialog(
                                                  title: Text('Alerta', textAlign: TextAlign.left,),
                                                  content: Text('¿Deseas eliminar el articulo del carrito?'),
                                                  shape: RoundedRectangleBorder(
                                                    borderRadius: BorderRadius.circular(10),
                                                  ),
                                                  insetPadding: EdgeInsets.symmetric(horizontal: 50),
                                                  actions: [
                                                    TextButton(
                                                      child: const Text('Cancelar'),
                                                      onPressed: () =>  Navigator.pop(_),
                                                    ),
                                                    TextButton(
                                                      child: const Text('Eliminar'),
                                                      onPressed: (() {
                                                        Navigator.pop(_);
                                                        setState(() {
                                                          _cart.remove(item);
                                                        });
                                                      }),
                                                    )
                                                  ],
                                                ));
                                              //_cart.remove(item);
                                            }
                                            setState(() {});
                                            

                                          }):new Container(),
                                          new Text(items.toString()),
                                          new IconButton(
                                            icon: new Icon(Icons.add),
                                            onPressed: ()=>setState(()=>items++)),
                                      ],
                                    ), 
                                  ],
                                ),

                                trailing: GestureDetector(
                                  child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Icon(
                                        Icons.delete,
                                          color: Colors.red,
                                          size: 30.0,
                                        ),
                                    ],
                                  ),
                                  onTap: () {
                                    setState(() {
                                      _cart.remove(item);
                                    });
                                  }

ProductsModel.dart

I also share the product model file

class ProductsModels {
  late String name;
  late String slug;
  late String image;
  late String pricebase;
  late String description;

  ProductsModels({required this.name, required this.slug, required this.image, required this.pricebase, required this.description});

  ProductsModels.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    slug = json['id'];
    image = json['image'];
    pricebase = json['price_base'];
    description = json['description'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['slug'] = this.slug;
    data['image'] = this.image;
    data['pricebase'] = this.pricebase;
    data['description'] = this.description;
    return data;
  }
}

Image

0 Answers
Related