Home > front end >  How to update multiple fields of class at once in dart?
How to update multiple fields of class at once in dart?

Time:01-31

Hi I'm new to dart and flutter and I want to create a method that update multiple fields at once.

For example, suppose there is a class named User, and it looks like this:

class User {
  int      id;
  String   password;
  String   firstName;
  String   lastName;
  String   nickName;
  String   gender;
  DateTime birthday;
  String   phoneNumber;
  String   address;

  ...
}

In this example, an instance of User will have a lot of fields and it's awkward to update multiple fields if you don't intend to update all of them.

So, when you update only password, nickName, phoneNumber and address, instead of reassigning a new User instance like this:

user = User(
  id          : 0,
  password    : 'xxxxxxx',
  firstName   : 'Hanako',
  lastName    : 'Tanaka',
  nickName    : 'Tanako',
  gender      : 'female',
  birthday    : DateTime(2000, 1, 1),
  phoneNumber : 'xxxxxxxxxxx',
  address     : 'xxxxxxxxxxx'
);

I want to update them like this:

user.updateUser({
  password    : 'xxxxxx',
  nickName    : 'Tanako',
  phoneNumber : 'xxxxxxxxxxx',
  address     : 'xxxxxxxxxxx'
});

Please tell me if there is a way to create a method that update multiple fields at once like this.

Thanks,

CodePudding user response:

you can do this like this

class User {
int id;
String password;
String firstName;
String lastName;
String nickName;
String gender;
DateTime birthday;
String phoneNumber;
String address;

User({
  required this.id,
  required this.password,
  required this.firstName,
  required this.lastName,
  required this.nickName,
  required this.gender,
  required this.birthday,
  required this.phoneNumber,
  required this.address,
});

updateUser({
  int? id,
  String? password,
  String? firstName,
  String? lastName,
  String? nickName,
  String? gender,
  DateTime? birthday,
  String? phoneNumber,
  String? address,
}) {
  this.id = id ?? this.id;
  this.password = password ?? this.password;
  this.firstName = firstName ?? this.firstName;
  this.lastName = lastName ?? this.lastName;
  this.nickName = nickName ?? this.nickName;
  this.gender = gender ?? this.gender;
  this.birthday = birthday ?? this.birthday;
  this.phoneNumber = phoneNumber ?? this.phoneNumber;
  this.address = address ?? this.address;
}
}

when you don't give a property name it will not update that field of the object for example if you want to update only firstName and lastName you can do it like this

user.updateUser(firstName:"Nao",lastName:"COMATSU");

and all other fields will not be updated

  • Related