skip to Main Content

I’m using provider to add items to my cart, but when I add items to the cart and print the cart List,
it appears as the following

it appears as the following

Here is my function


class CartList extends ChangeNotifier {
  Map<String, CartModel> _cart = {};

  Map get cart => _cart;

void addToCart({required String productId,price,title,image}){
    // When a item is added to the cart that already exists, update quantity by one
    if(_cart.containsKey(productId)){
      _cart.update(productId,(value)=> CartModel(key: value.key,name:value.name,image:value.image,price:value.price,quantity: value.quantity! + 1,totalPrice: 0));
    } 
    // If the item is not in the cart, add it
    else {
      _cart[productId] = CartModel(key: productId,name:title,image:image,price:price,quantity: 1,totalPrice: 0);
    }
    notifyListeners();
  }
}

I’m not sure if that structure is right but I just want to print each property inside my cartPage.

here is my cartPage.dart:


class cartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final shoppingList = Provider.of<CartList>(context);
    final items = shoppingList.cart;

    return Scaffold(
      appBar: AppBar(title: Text("Cart"),
      
      ),
      body: SafeArea(
        child: Column(
        children: [
          ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return ListTile(
                
                title: Text(item.name),
                subtitle: Text('${item.quantity}'),
                
                // trailing: IconButton(
                //   icon: Icon(Icons.delete),
                //   onPressed: () => shoppingList.removeItem(index),
                // ),
              );
            },
          ),
        ],
        ),
      )
    );
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Answered , It's correct to see this value when printing your cart. However, you can still map through your values using ListView.builder.


  2. in your CartModel class you have to add an ovverride of toString so that when you print that class, it prints you whatever value you put in the toString method:

       class CartModel {
        
        final String aRandomProperty;
        
        @override
          String toString() {
            return 'aRandomProperty: ${aRandomProperty}';
          }
    

    now when you try to print it, it will work

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search