admin管理员组

文章数量:1278721

import 'package:final_project/models/offer.dart';
import 'package:final_project/provider/cart_list_provider.dart';
import 'package:final_project/widgets/cart_item.dart';
import 'package:flutter/material.dart';
import 'package:final_project/provider/cart_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:developer';

//use bool to decide how to display  the widget, whether from productdetailsscreen or from tabs screen
class CartScreen extends ConsumerStatefulWidget {
  const CartScreen({super.key});

  @override
  ConsumerState<CartScreen> createState() {
    return _CartsScreenState();
  }
}

class _CartsScreenState extends ConsumerState<CartScreen> {
  // **double calculateTotalPrice(List<Offer> itemBag) {
  //   double sum = 0;
  //   
  //     for (final item in itemBag) {
  //       sum += item.productPrice * item.quantityChosen;
  //     }
  //  
  //   return sum;
  // }**

  @override
  Widget build(BuildContext context) {
    
    final itemBag = ref.watch(itemBagProvider);

    print(itemBag);
    // print(inspect(itemBag));
    // print(itemBag[0]);
    Widget mainContent = const Center(
      child: Text("No items have been added to the cart"),
    );
    if (itemBag.isNotEmpty) {
      mainContent = Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              child: ListView.builder(
                itemBuilder: (ctx, index) => Dismissible(
                  key: ValueKey(itemBag[index]),
                  onDismissed: (direction) {
                    ref
                        .read(itemBagProvider.notifier)
                        .removeItem(itemBag[index].offerId);
                    ScaffoldMessenger.of(context).clearSnackBars();
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content:
                            Text("This item has been removed from the cart"),
                        duration: Duration(seconds: 3),
                        dismissDirection: DismissDirection.horizontal,
                      ),
                    );
                  },
                  background: const Card(
                    color: Colors.red,
                    margin: EdgeInsets.all(10),
                  ),
                  child: CartItem(
                    item: itemBag[index],
                  ),
                ),
                itemCount: itemBag.length,
              ),
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                Text("Total"),
                const Spacer(),
                Text(ref.watch(itemBagProvider.notifier).calculateTotalPrice().toString()),
              ],
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
              },
              style: ElevatedButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15),
                ),
                backgroundColor: const Color.fromRGBO(92, 229, 26, 1.0),
                padding: const EdgeInsets.symmetric(vertical: 15),
              ),
              child: Text(
                "Proceed to Checkout",
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.bodyLarge!.copyWith(
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
              ),
            )
          ],
        ),
      );
    }

    return mainContent;
  }
}
import "package:final_project/models/offer.dart";
import "package:flutter_riverpod/flutter_riverpod.dart";
import 'package:final_project/data/dummy_data.dart';

class ItemBagNotifier extends StateNotifier<List<Offer>> {
  ItemBagNotifier() : super([]);

  // Add new item

  void addNewItemBag(Offer productModel) {
    state = [...state, productModel];
  }

  // Remove item

  void removeItem(String pid) {
    state = [
      for (final product in state)
        if (product.offerId != pid) product,
    ];
  }

  void incrementQty(String pid) {
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        offer.copyWith(quantityChosen: offer.quantityChosen += 1);
      }
    }
  }

  void incrementQtyState(String pid) {
    for (final offer in state) {
      if (offer.offerId == pid) {
        offer.copyWith(quantityChosen: offer.quantityChosen += 1);
      }
    }
  }

  void decreaseQtyState(String pid) {
    for (final offer in state) {
      if (offer.offerId == pid) {
        offer.copyWith(quantityChosen: offer.quantityChosen -= 1);
      }
    }
  }

  void incrementPrice(String pid) {
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        offer.copyWith(totalPrice: offer.productPrice * offer.quantityChosen);
      }
    }
  }

  //decrementPrice
  void decrementPrice(String pid) {
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        offer.copyWith(totalPrice: offer.totalPrice - offer.productPrice);
      }
    }
  }

  void decreaseQty(String pid) {
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        offer.copyWith(
          quantityChosen: offer.quantityChosen -= 1,
        );
      }
    }
  }

  int getQuantityState(String pid) {
    int qty = 0;
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        qty = offer.quantityChosen;
      }
    }
    return qty;
  }

  int getQuantityII(String pid) {
    int qty = 0;
    for (final offer in dummyOffers) {
      if (offer.offerId == pid) {
        qty = offer.quantityChosen;
      }
    }
    return qty;
  }

  double calculateTotalPrice() {
    double sum = 0;
    for (final item in state) {
      sum += item.productPrice * item.quantityChosen;
    }
    print(sum);
    return sum;
  }
}

final itemBagProvider =
    StateNotifierProvider<ItemBagNotifier, List<Offer>>((ref) {
  return ItemBagNotifier();
});

final priceCalcProvider = StateProvider<double>((ref) {
  final itemBag = ref.watch(itemBagProvider);

  double sum = 0;
  for (var element in itemBag) {
    sum += element.productPrice * element.quantityChosen;
  }
  return sum;
});

The itemBagProvider class is the second code snipper but i am not using the priceCalcProvider because it does not work.

So my issue is that I am trying to get the total price of all the items in the cart based on the quantity chosen for each item, but it does not update until after I leave the carts screen and come back to it and I am managing the calculateTotalPrice method in a riverpod state class. The body of the calculateTotalPrice method is the one where there are double forward slashes in front it and i is in bold.

So I expect that the anytime I increase the quantity of an item the total price should get updated

本文标签: riverpodIs there a way of forcing flutter to update the UIStack Overflow