如何解决手势捕获的异常处理手势时抛出以下 NoSuchMethodError
我是新手,我正在尝试将产品添加到购物车,但是当我单击添加按钮时,它显示 collection
方法在 null 上调用
我用来将产品添加到用户购物车的功能:
void checkItemInCart(String shortInfoAsID,BuildContext context) {
Constants.sharedPreferences
.getStringList(Constants.userCartList)
.contains(shortInfoAsID)
? Fluttertoast.showToast(msg: "Item is already in Cart.")
: addItemToCart(shortInfoAsID,context);
}
addItemToCart(String shortInfoAsID,BuildContext context) {
List tempCartList =
Constants.sharedPreferences.getStringList(Constants.userCartList);
tempCartList.add(shortInfoAsID);
Constants.firestore
.collection(Constants.collectionUser)
.document(Constants.sharedPreferences.getString(Constants.userUID))
.updateData({
Constants.userCartList: tempCartList,}).then((v) {
Fluttertoast.showToast(msg: "Item Added to Cart Successfully.");
Constants.sharedPreferences
.setStringList(Constants.userCartList,tempCartList);
Provider.of<CartItemCounter>(context,listen: false).displayResult();
});
}
我还有常量文件:
class Constants {
static const String appName = 'App name';
static SharedPreferences sharedPreferences;
static FirebaseUser user;
static FirebaseAuth auth;
static Firestore firestore;
static String collectionUser = "users";
static String collectionorders = "orders";
static String userCartList = 'userCart';
static String subCollectionAddress = 'userAddress';
static final String userName = 'name';
static final String userEmail = 'email';
static final String userPhotoUrl = 'photoUrl';
static final String userUID = 'uid';
static final String userAvatarUrl = 'url';
static final String addressID = 'addressID';
static final String totalAmount = 'totalAmount';
static final String productID = 'productIDs';
static final String paymentDetails = 'paymentDetails';
static final String orderTime = 'orderTime';
static final String isSuccess = 'isSuccess';
}
我得到的错误是:
════════ Exception caught by gesture ═══════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'collection' was called on null.
Receiver: null
Tried calling: collection("users")
When the exception was thrown,this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 addItemToCart
package:shipit/Store/storehome.dart:371
#2 checkItemInCart
package:shipit/Store/storehome.dart:362
我希望你能帮助我谢谢你提前感谢它。
解决方法
发生这种情况是因为 Constants.firestore
是 null
。您需要设置 Constants.firestore
以包含 Firestore
的实例。例如,您可以这样做:
// in lib/main.dart
void main() {
WidgetsFlutterBinding.ensureInitialized(); // make sure plugins are initialized
Constants.firestore = Firestore.instance; // Constants.firestore is not null after this line
runApp(MyApp()); // launch the app
}
如果您将 main()
方法设置为如下所示,当您尝试在小部件/状态管理中使用它时,Constants.firestore
将永远不会为 null。
您可能还想考虑对 Constants
中的其他内容也这样做(例如 FirebaseAuth
、SharedPreferences
等)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。