Исключение, обнаруженное жестом При обработке жеста возникла следующая ошибка NoSuchMethodError.
Я новичок с флаттером, я пытаюсь добавить товар в корзину, но когда я нажимаю кнопку добавления, он показывает, что
collection
Метод вызывается при нулевом значении функции, которую я использую для добавления продукта в корзину пользователя:
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
Я надеюсь, что вы можете помочь мне заранее поблагодарить вас.
1 ответ
Это происходит потому, что
null
. Вам нужно установить, чтобы он содержал экземпляр
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
никогда не будет нулевым, когда вы попытаетесь использовать его в своих виджетах / управлении состоянием.
Вы также можете подумать о том, чтобы сделать это для других вещей в
Constants
тоже (например,
FirebaseAuth
,
SharedPreferences
так далее)