Home > Blockchain >  Flutter: _CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>
Flutter: _CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>

Time:02-05

When I create a new user the error (_CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast)) apears at User.fromSnap ...as Map<stringm,dynamic> and firebase creates the user auth but not the user data

Can you help me to add array of array of objects to firebase?

Thanks!

user.dart

    class User {
      final String uid;
      final String name;
      final List<Game> game;
    
      User(
          {required this.uid,
          required this.name,
          required this.game});
    
      factory User.fromSnap(DocumentSnapshot snap) {
        var snapShot = snap.data() as Map<String, dynamic>;
    
        return User(
            uid: snapShot['uid'],
            name: snapShot['name'],
            game: snapShot['game']);
      }
    
      Map<String, dynamic> toJson() => {
            'uid': uid,
            'name': name,
            'game': game,
          };
    }
    
    class Game{
      String rolName;
      bool alive;
    
      Game({required this.rolName, required this.alive});
    
      factory Game.fromSnap(Map<String, dynamic> snap) {
        return Game(rolName: snap['rolName'], alive: snap['alive']);
      }
    }

auth.dart

 class AuthMethods with ChangeNotifier {
    ...

  Future<String> singUpUser(
      {required String email,
      required String password,
      required String namee}) async {
    String res = 'Error';
    try {
      if (email.isNotEmpty ||
          password.isNotEmpty ||
          name.isNotEmpty ) {
        UserCredential cred = await _auth.createUserWithEmailAndPassword(
            email: email, password: password);

        model.User _user = model.User(
            uid: cred.user!.uid,
            name: name,
            game: [model.Game(rolName: 'default', alive: false)]);
        await _firestore
            .collection("users")
            .doc(cred.user!.uid)
            .set(_user.toJson());

        res = 'success';
      } else {
        res = "Please enter all the fields";
      }
    } catch (err) {
      res = err.toString();
    }
    return res;
  }

CodePudding user response:

Your factory looks right. But you're sending it nothing...the snap is null is what that error is telling you.

  •  Tags:  
  • Related