【问题标题】:How do I resolve this StackOverflow Error如何解决此 StackOverflow 错误
【发布时间】:2020-11-30 11:31:00
【问题描述】:

我正在尝试使用以下方法从提供者小部件返回的 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,
          ))
        ],
      ),
    );
  }
}

如何获得正确的值?

【问题讨论】:

    标签: flutter dart error-handling maps flutter-provider


    【解决方案1】:

    我能看到不正确的一点是

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

    应该是这样的

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-12
        • 2012-02-14
        • 2015-04-12
        • 2016-06-21
        • 2020-11-16
        • 1970-01-01
        相关资源
        最近更新 更多