Home > Software engineering >  Flutter How to set usermodel
Flutter How to set usermodel

Time:12-02

Im trying CRUD operations with GetX to Firebase. I also created my database. Here the codes:

    class DataBaseFB {
  FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;

  Future<bool> createNewUser(UserModel userModel) async {
    try {
      await _firebaseFirestore.collection("customer").doc(userModel.uid).set({
        "name": userModel.name,
        "email": userModel.email,
      });
      return true;
    } on FirebaseException catch (e) {
      debugPrint(e.code);
      return false;
    }
  }
}

And here my UserModel:

class UserModel {
  String uid;
  String name;
  String? email;

  UserModel(
    this.uid,
    this.email,
    this.name,
  );

  UserModel.fromDocumentSnapshot(this.uid, this.name, this.email,
      {DocumentSnapshot? documentSnapshot}) {
    uid = documentSnapshot!.id;
    name = documentSnapshot["name"];
    email = documentSnapshot["email"];
  }
}

So, I am trying to put that new user in firebase database like this;

void createAccount(String email, String password, String name) async {
    try {
      UserCredential _userCredential =
          await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      User? _yeniUser = _userCredential.user;
      String _yeniUserUID =
          _userCredential.user!.uid; 
      UserModel _user = UserModel(
        {}
      ); *// Here is the error line.*
    } on FirebaseException catch (e) {
      Get.snackbar("Error", e.code);
    }
  }

Error code:

3 positional argument(s) expected, but 1 found. Try adding the missing arguments.

I tried this but it doesn't work.

    UserModel _user = UserModel(
                {
'name': name,
'email': _yeniUser.email,
'uid': _yeniUserUID,

}
              ); 

Where am I doing wrong ? Thanks.

CodePudding user response:

Since your model is defined like this

UserModel(
  this.uid,
  this.email,
  this.name,
);

// You define your _user like this:
UserModel _user = UserModel(_yeniUserUID, _yeniUser.email, name);`
// make sure the order is right. uid first then email then name.

If you model was defined like this:

UserModel({ // <-- Note the opening curly bracket
  this.uid,
  this.email,
  this.name,
});         // <-- and closing curly bracket

// Then you would define your _user like this:
UserModel _user = UserModel(
  uid: _yeniUserUID,
  name: name,
  email: _yeniUser.email,
);
// order does not matter. Recommended.
  • Related