Home > Blockchain >  flutter what is the point of that usage
flutter what is the point of that usage

Time:12-29

when I'm looking for codes in open resource flutter project, a user used a model like this. I could not get the idea here. Does not it need to use a getter what is the point in the curly braces term:

_email = email;
_password = password;
class LoginModel {
  String? _email;
  String? _password;

  LoginModel({
    String? email,
    String? password,
  }) {
    _email = email;
    _password = password;
  }

  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["email"] = _email;
    map["password"] = _password;
    return map;
  }

  set email(String value) => _email = value;
  set password(String value) => _password = value;
}

CodePudding user response:

Actually, you have a couple of options there:

  1. Instead of having the class parameters as private and named, you could have them only private and do like this (if you want them to be private, they can't be named because the other classes wouldn't be able to see the names):

    LoginModel(
            this._email,
            this._password,
          )
    
  2. You could make them named and necessary to instantiate the class by adding the required tag with them and removing the private indicator _, like this:

    LoginModel({
            required this.email,
            required this.password,
          }) 
    
  3. Or you could just make them named and not necessary (since they are nullable):

    LoginModel({
            this.email,
            this.password,
          }) 
    

CodePudding user response:

I highly recommend watching some language overviews for dart or checking out the documentation here. But to answer your questions:

  1. The underscore shows that the variables are meant to be private.
  2. The curly braces show optional parameters. So someone initializing the login model could do any of the following:
    LoginModel()
    LoginModel(email: "")
    LoginModel(password: "")
    LoginModel(email: "", password: "")

Non optional parameters are initialized outside of curly braces. If I wanted email to be required and not password I could do the following: LoginModel(String email, {String? password})

  • Related