0

My Flutter app shows the following error:

E/flutter (13058): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. E/flutter (13058): Receiver: null E/flutter (13058): Tried calling:

This error points to 3 different pieces of code which will be listed below:

user.dart:

    UserModel.fromSnapshot(DocumentSnapshot snapshot){
    _name = snapshot.data()[NAME];
      _email = snapshot.data()[EMAIL];
    _id = snapshot.data()[ID];
    _phone = snapshot.data()[PHONE];
    _token = snapshot.data()[TOKEN];
    _photo = snapshot.data()[TOKEN];
    _votes = snapshot.data()[VOTES];
    _trips = snapshot.data()[TRIPS];
    _rating = snapshot.data()[RATING];
  }

user.dart:

    Future<UserModel> getUserById(String id) =>
      firebaseFiretore.collection(collection).doc(id).get().then((doc) {
        return UserModel.fromSnapshot(doc);
      });

user.dart:

    _onStateChanged(User firebaseUser) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (firebaseUser == null) {
      _status = Status.Unauthenticated;
    } else {
      _user = firebaseUser;
      await prefs.setString("id", firebaseUser.uid);

      _userModel = await _userServices.getUserById(user.uid).then((value) {
        _status = Status.Authenticated;
        return value;
      });
    }
    notifyListeners();
  }

How do I solve this error? If any further information required, do let me know.

Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17
Praveesh Ramroop
  • 205
  • 2
  • 11

1 Answers1

0

Make return type nullable

Future<UserModel?> getUserById(String id) =>
      firebaseFiretore.collection(collection).doc(id).get().then((doc) {
        if(doc.exist) {
          return null;
        }
        return UserModel.fromSnapshot(doc);
      });
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17