How do I resolve this StackOverflow Error

Issue

I’m trying to get the values from a Map object returned from a Provider Widget using:
final cart = Provider.of<Cart>(context);

but I’m getting this StackOverFlowError.

The Error:

═════ Exception caught by widgets library ═══════════════════════════════════
The following StackOverflowError was thrown building:
Stack Overflow

When the exception was thrown, this was the stack
#0      new _InternalLinkedHashMap (dart:collection-patch/compact_hash.dart:157:3)
#1      new Map._fromLiteral (dart:core-patch/map_patch.dart:16:19)
#2      Cart.items           package:shop/providers/cart.dart:9
#3      Cart.items           package:shop/providers/cart.dart:9

This is my provider class:

class Cart with ChangeNotifier {
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {...items};
  }

  //returns no of product in cart
  int get itemCount {
    return _items.length;
  }

  double get totalAmount {
    double total = 0.0;
    _items.forEach(
        (key, cartItem) => total += (cartItem.price * cartItem.quantity));

    return total;
  }

  //add item to cart if it does not exist or add an extra quantity if it exist
  void addItem(String productId, double price, String title) {
    if (_items.containsKey(productId)) {
      _items.update(
          productId,
          (existingCartItem) => CartItem(
              id: existingCartItem.id,
              title: existingCartItem.title,
              price: existingCartItem.price,
              quantity: existingCartItem.quantity + 1));
    } else {
      _items.putIfAbsent(
          productId,
          () => CartItem(
              id: DateTime.now().toString(),
              title: title,
              price: price,
              quantity: 1));
    }

    notifyListeners();
  }
}

and i use it here:

class CartScreen extends StatelessWidget {
  static const routeName = 'cart-screen';
  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<Cart>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Your Cart'),
      ),
      body: Column(
        children: [
          Card(
            margin: const EdgeInsets.all(15),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(
                    'Total',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'Lato-Bold',
                    ),
                  ),
                  Spacer(),
                  Chip(
                    label: Text(
                      '\$${cart.totalAmount}',
                      style: TextStyle(
                        color:
                            Theme.of(context).primaryTextTheme.headline6.color,
                      ),
                    ),
                    backgroundColor: Theme.of(context).primaryColor,
                  ),
                  FlatButton(
                    child: Text('ORDER NOW'),
                    onPressed: () {},
                    textColor: Theme.of(context).primaryColor,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 10),
          Expanded(
              child: ListView.builder(
            itemBuilder: (ctx, index) {
               return Text(cart.items.values.toList()[index].title); // this is where i have a problem
              // return CartItem(cart.items.values.toList()[index].id, cart.items.values.toList()[index].price,
              //     cart.items.values.toList()[index].quantity, cart.items.values.toList()[index].title);
            },
            itemCount: cart.itemCount,
          ))
        ],
      ),
    );
  }
}

How do I get the values right?

Solution

One thing that I can see is not right is

 Map<String, CartItem> get items {
    return {...items};
  }

that should be

 Map<String, CartItem> get items {
     return {..._items};
  }

Answered By – sonic

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *