简体   繁体   English

NoSuchMethodError: 在 null 上调用了方法“[]”。 接收者:null 尝试调用:[]("favorites")

[英]NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("favorites")

On each user auth and user creation, I have an error message where the method is called on null.在每个用户身份验证和用户创建时,我都会收到一条错误消息,其中在 null 上调用了该方法。

The user is created when I sign up but it prevents me to continue the use without having to restart the apps.用户是在我注册时创建的,但它阻止我继续使用而无需重新启动应用程序。

I placed all the call related to user creation in firebase, I can not find the root cause of the null.我把所有与用户创建相关的调用都放在了 firebase 中,我找不到 null 的根本原因。

在此处输入图片说明


class AuthNotifier with ChangeNotifier {
  FirebaseUser _user;
  FirebaseUser get user => _user;

  void setUser(FirebaseUser user) {
    _user = user;
    _createUserDocument();
    if (user != null) {
      _createUserDocument();
    }
    notifyListeners();
  }

  void _createUserDocument() async {
    CollectionReference users = Firestore.instance.collection('Users');
    DocumentSnapshot user_document = await users.document(_user.uid).get();
    if (!user_document.exists) {
      // Create a document for the user if he doesn't have one
      users.document(_user.uid).setData({
        'favorites': []
      }
      );
    }
  }

  Future<void> toggleFavorite(String foodId) async {
    CollectionReference users = Firestore.instance.collection('Users');
    DocumentSnapshot user_document = await users.document(_user.uid).get();

    // If using collectionGroup, we can directly filter the foodId without looping through it.
    // Fetch and see if it is already in the list // TODO: Use class-wide, static, event-updated instance
    for (dynamic reference in user_document.data['favorites']) {
      if (reference.documentID == foodId) {
        // Remove it from the list and exit so it doesn't get added later in the function
        users.document(_user.uid).updateData({'favorites': FieldValue.arrayRemove([reference])}).catchError((error) => print("Failed to remove favorite element: ${error}"));
        notifyListeners();
        return;
      }
    }

    // Get the matching food DocumentReference object
    var food = await Firestore.instance.collection('Foods').document(foodId).get();
    // Add to the favorite list if it wasn't
    users.document(_user.uid).updateData({'favorites': FieldValue.arrayUnion([food.reference])}).catchError((error) => print("Failed to add new favorite element : ${error}"));
    notifyListeners();
  }

  Future<bool> isFavorite(String foodId) async {
    List<dynamic> favorites = await _getFavorites();
    for (DocumentReference favorite in favorites) {
      if (favorite.documentID == foodId) {
        return true;
      }
    }
    return false;
  }

  Future<List<dynamic>> getFavorites() async {
    List<dynamic> favorites = await _getFavorites();
    List<String> favorites_documentid = [];
    favorites.forEach((reference) { favorites_documentid.add(reference.documentID); });
    return favorites_documentid;
  }

  Future<List<dynamic>> _getFavorites() async {  // TODO: Use class-wide list that updates only when a a favorite is added or removed. Even listen to a snapshot for this, if there are lots of favorites.
    DocumentSnapshot snapshot = await Firestore.instance
        .collection('Users').document(_user.uid).get();
    return snapshot.data['favorites'];  // DocumentReference
  }

}

You need to await for async operations to complete.您需要await异步操作完成。


  Future<void> setUser(FirebaseUser user) {
    _user = user;
    await _createUserDocument();
    if (user != null) {
      await _createUserDocument();
    }
    notifyListeners();
  }

  Future<void> _createUserDocument() async {
    CollectionReference users = Firestore.instance.collection('Users');
    DocumentSnapshot user_document = await users.document(_user.uid).get();
    if (!user_document.exists) {
      // Create a document for the user if he doesn't have one
      await users.document(_user.uid).setData({
        'favorites': []
      }
      );
    }
  }

And await for setUser() as well.await setUser()

Update.更新。 Use snapshot.data() instead of snaphot.data :使用snapshot.data()而不是snaphot.data

  Future<List<dynamic>> _getFavorites() async { 
    DocumentSnapshot snapshot = await Firestore.instance
        .collection('Users').document(_user.uid).get();
    return snapshot.data()['favorites'];  // DocumentReference
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NoSuchMethodError(NoSuchMethodError:在 null 上调用了方法“[]”。接收方:null 尝试调用:[](0)) - NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: [](0)) NoSuchMethodError: 在 null 上调用了方法“+”。 接收者:null 尝试调用:+(&quot; &quot;) - NoSuchMethodError: The method '+' was called on null. Receiver: null Tried calling: +(" ") NoSuchMethodError(NoSuchMethodError:在 null 上调用了“forEach”方法。接收方:null 尝试调用:forEach(Closure:(动态)=> Null)) - NoSuchMethodError (NoSuchMethodError: The method 'forEach' was called on null. Receiver: null Tried calling: forEach(Closure: (dynamic) => Null)) NoSuchMethodError:在 null 上调用了方法“[]”。 接收器:null。 尝试调用:[](“名称”) - NoSuchMethodError: The method '[]' was called on null. Receiver: null. Tried calling: [](“name”) 我该如何解决这个错误? 'NoSuchMethodError' 在 null 上调用了方法 '[]'。 接收器:null。 尝试调用:[]("title") - how can i solve this error? 'NoSuchMethodError' The method '[]' was called on null. Receiver: null. Tried Calling: []("title") NoSuchMethodError(NoSuchMethodError:在 null 上调用了方法“toDate”。接收方:null 尝试调用:toDate()) - NoSuchMethodError (NoSuchMethodError: The method 'toDate' was called on null. Receiver: null Tried calling: toDate()) NoSuchMethodError (NoSuchMethodError: The method &#39;[]&#39; was called on null. Receiver: null Tried calls: [](&quot;title&quot;)) - NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: [](“title”)) NoSuchMethodError(NoSuchMethodError:在 null 上调用了方法“add”。接收方:null 尝试调用:add(“CategoresList”的实例)) - NoSuchMethodError (NoSuchMethodError: The method 'add' was called on null. Receiver: null Tried calling: add(Instance of 'CategoresList')) 在构建 Home() 时引发了以下 NoSuchMethodError:在 null 上调用了方法“&gt;”。 接收方:null 尝试呼叫:&gt;(1) - The following NoSuchMethodError was thrown building Home(): The method '>' was called on null. Receiver: null Tried calling: >(1) Flutter:NoSuchMethodError:在 null 上调用了方法“fetchByID”。 接收方:null 尝试调用:fetchByID(2) - Flutter: NoSuchMethodError :The method 'fetchByID' was called on null. Receiver: null Tried calling: fetchByID(2)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM