Flutter “如何确定方法”;包含键“;调用空颤振

Flutter “如何确定方法”;包含键“;调用空颤振,flutter,flutter-provider,Flutter,Flutter Provider,我是Flitter的初学者,一直在开发一款电子商务应用程序。我使用提供程序包将产品添加到购物车,但出现以下错误: 我的颤振医生也很好。我只有在尝试将项目添加到购物车时才遇到此问题。任何帮助都将不胜感激 ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ The following NoSuchMethodError was thrown while

我是Flitter的初学者,一直在开发一款电子商务应用程序。我使用提供程序包将产品添加到购物车,但出现以下错误: 我的颤振医生也很好。我只有在尝试将项目添加到购物车时才遇到此问题。任何帮助都将不胜感激

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'containsKey' was called on null.
Receiver: null
Tried calling: containsKey("p1")
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:51:5)
#1      Cart.addItem 
package:shop_stop/…/components/cart.dart:33
#2      _ProductItemState.build.<anonymous closure> 
package:shop_stop/widgets/product_item.dart:80

══╡ 用手势捕捉异常╞═══════════════════════════════════════════════════════════════════
处理手势时引发以下NoSuchMethodError:
对null调用了方法“containsKey”。
收件人:空
已尝试呼叫:containsKey(“p1”)
引发异常时,这是堆栈:
#0 Object.noSuchMethod(省道:核心补片/对象补片。省道:51:5)
#1.附加项
包装:shop_stop/../components/cart.省道:33
#2_ProductItemState.build。
包装:购物站/小工具/产品项目。省道:80
我的购物车提供商:

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    @required this.id,
    @required this.title,
    @required this.quantity,
    @required this.price,
  });
}

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

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

  int get itemCount {
    return _items.length;
  }

  void addItem(
    String productId,
    double price,
    String title,
  ) {
    if (_items.containsKey(productId)) {
      // change quantity...
      _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();
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shop_stop/screens/cart/components/cart.dart';

import '../views/product_details.dart';
import '../models/product.dart';

class ProductItem extends StatefulWidget {
  @override
  _ProductItemState createState() => _ProductItemState();
}

class _ProductItemState extends State<ProductItem> {
  @override
  Widget build(BuildContext context) {
    final products = Provider.of<Product>(context, listen: false);
    final cart = Provider.of<Cart>(context, listen: false);
    return Container(
      child: GestureDetector(
        onTap: () {
          Navigator.of(context)
              .pushNamed(ProductDetails.routeName, arguments: products.id);
        },
        child: Card(
          color: Colors.white,
          elevation: 6,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              //product image
              Image(image: AssetImage('assets/laptop.jpg')),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                //item name and fav button
                child: Flex(
                  direction: Axis.horizontal,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      products.name,
                      style: Theme.of(context)
                          .textTheme
                          .headline1
                          .copyWith(fontSize: 16, color: Colors.black),
                    )),
                    //add-to-fav button
                    Consumer<Product>(
                      builder: (ctx, product, child) => IconButton(
                          icon: Icon(
                            products.isFav
                                ? Icons.favorite
                                : Icons.favorite_border,
                            color: Colors.red,
                          ),
                          onPressed: () {
                            products.toggleFav();
                          }),
                    )
                  ],
                ),
              ),
              // price and buy button
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                child: Flex(
                  direction: Axis.horizontal,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      "\$ " + products.price.toString(),
                      style: Theme.of(context).textTheme.headline1.copyWith(
                          color: Theme.of(context).primaryColor, fontSize: 15),
                    )),
                    SizedBox(
                      width: 60,
                      child: RaisedButton(
                        onPressed: () {
                          cart.addItem(
                              products.id, products.price, products.name);
                        },
                        color: Colors.orange,
                        child: Text(
                          "Buy",
                          style: TextStyle(fontFamily: 'Prompt', fontSize: 14),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

类CartItem{
最终字符串id;
最后的字符串标题;
最终整数数量;
最终双倍价格;
卡蒂姆({
@需要这个.id,
@需要这个标题,
@所需数量,
@需要这个价格,
});
}
使用ChangeNotifier初始化购物车{
地图项目;
映射获取项目{
返回{…\u items};
}
int获取项目计数{
返回_items.length;
}
无效附加项(
字符串productId,
双倍价格,
字符串标题,
) {
if(_items.containsKey(productId)){
//更改数量。。。
_items.update(
productId,
(existingCartItem)=>CartItem(
id:existingCartItem.id,
标题:existingCartItem.title,
价格:existingCartItem.price,
数量:现有CartItem.quantity+1,
),
);
}否则{
_项目。putIfAbsent(
productId,
()=>CartItem(
id:DateTime.now().toString(),
标题:标题,,
价格:价格,
数量:1,
),
);
}
notifyListeners();
}
}
我的产品项目:

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    @required this.id,
    @required this.title,
    @required this.quantity,
    @required this.price,
  });
}

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

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

  int get itemCount {
    return _items.length;
  }

  void addItem(
    String productId,
    double price,
    String title,
  ) {
    if (_items.containsKey(productId)) {
      // change quantity...
      _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();
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shop_stop/screens/cart/components/cart.dart';

import '../views/product_details.dart';
import '../models/product.dart';

class ProductItem extends StatefulWidget {
  @override
  _ProductItemState createState() => _ProductItemState();
}

class _ProductItemState extends State<ProductItem> {
  @override
  Widget build(BuildContext context) {
    final products = Provider.of<Product>(context, listen: false);
    final cart = Provider.of<Cart>(context, listen: false);
    return Container(
      child: GestureDetector(
        onTap: () {
          Navigator.of(context)
              .pushNamed(ProductDetails.routeName, arguments: products.id);
        },
        child: Card(
          color: Colors.white,
          elevation: 6,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              //product image
              Image(image: AssetImage('assets/laptop.jpg')),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                //item name and fav button
                child: Flex(
                  direction: Axis.horizontal,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      products.name,
                      style: Theme.of(context)
                          .textTheme
                          .headline1
                          .copyWith(fontSize: 16, color: Colors.black),
                    )),
                    //add-to-fav button
                    Consumer<Product>(
                      builder: (ctx, product, child) => IconButton(
                          icon: Icon(
                            products.isFav
                                ? Icons.favorite
                                : Icons.favorite_border,
                            color: Colors.red,
                          ),
                          onPressed: () {
                            products.toggleFav();
                          }),
                    )
                  ],
                ),
              ),
              // price and buy button
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                child: Flex(
                  direction: Axis.horizontal,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      "\$ " + products.price.toString(),
                      style: Theme.of(context).textTheme.headline1.copyWith(
                          color: Theme.of(context).primaryColor, fontSize: 15),
                    )),
                    SizedBox(
                      width: 60,
                      child: RaisedButton(
                        onPressed: () {
                          cart.addItem(
                              products.id, products.price, products.name);
                        },
                        color: Colors.orange,
                        child: Text(
                          "Buy",
                          style: TextStyle(fontFamily: 'Prompt', fontSize: 14),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

导入“包装:颤振/材料.省道”;
导入“包:provider/provider.dart”;
导入“包装:shop_stop/screens/cart/components/cart.dart”;
导入“../views/product_details.dart”;
导入“../models/product.dart”;
类ProductItem扩展StatefulWidget{
@凌驾
_ProductItemState createState()=>\u ProductItemState();
}
类_ProductItemState扩展了状态{
@凌驾
小部件构建(构建上下文){
最终产品=Provider.of(上下文,listen:false);
final cart=Provider.of(上下文,侦听:false);
返回容器(
儿童:手势检测器(
onTap:(){
导航器(上下文)
.pushNamed(ProductDetails.routeName,参数:products.id);
},
孩子:卡片(
颜色:颜色,白色,
标高:6,
形状:
RoundedRectangleBorder(borderRadius:borderRadius.circular(10)),
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
//产品形象
图像(图像:AssetImage('assets/laptop.jpg')),
填充物(
填充:边集。对称(垂直:0,水平:10),
//项目名称和fav按钮
孩子:Flex(
方向:水平轴,
儿童:[
扩大(
子:文本(
产品名称,
风格:主题(上下文)
.文本主题
.标题1
.copyWith(字体大小:16,颜色:Colors.black),
)),
//添加到fav按钮
消费者(
生成器:(ctx、产品、子项)=>IconButton(
图标:图标(
产品.isFav
?图标。收藏
:Icons.favorite_边框,
颜色:颜色,红色,
),
已按下:(){
产品;
}),
)
],
),
),
//价格和购买按钮
填充物(
填充:边缘设置。对称(水平:10,垂直:0),
孩子:Flex(
方向:水平轴,
儿童:[
扩大(
子:文本(
“\$”+products.price.toString(),
样式:Theme.of(context).textTheme.headline1.copyWith(
颜色:主题。背景。原色,字体大小:15),
)),
大小盒子(
宽度:60,
孩子:升起按钮(
已按下:(){
购物车附加项(
products.id、products.price、products.name);
},
颜色:颜色。橙色,
子:文本(
“买”,
样式:TextStyle(fontFamily:'Prompt',fontSize:14),
),
),
)
],
),
),
],
),
),
),
);
}
}
更改
地图项目
映射_项={}

更改
地图项目
映射_项={}