如何解决此 StackOverflow 错误

我正在尝试从提供者小部件返回的 Map 对象中获取值: final cart = Provider.of<Cart>(context);

但我得到了这个 StackOverFlowError

错误:

═════ 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

这是我的提供者类:

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();
  }
}

我在这里使用它:

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,
          ))
        ],
      ),
    );
  }
}

我如何获得正确的值?

stack overflow How do I resolve this StackOverflow Error
原文答案
author avatar

接受的答案

我可以看到不正确的一件事是

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

那应该是

 Map<String, CartItem> get items {
     return {..._items}; // <-- missing undescore
  }

答案:

作者头像

你应该返回{..._items}。您忘记了 get 方法中的下划线