Flutter GetX Using custom object as Obs

6 min read

Usually, I use copyWith with reactive class and update them inside the controller

通常,我使用 copyWith使用反应类并在控制器内更新它们

Something like this

像这样的东西

class Controller extends GetxController {
  final Rx<User> _user = Rx<User>();

  submit() {
    _user.value = userModel.copyWith(...);
  }
}

或者

// on the model file
// we are going to make the entire class observable instead of each attribute
class User() {
  User({this.name = '', this.age = 0});
  String name;
  int age;
}

// on the controller file
final user = User().obs;
// when you need to update the user variable:
user.update( (user) { // this parameter is the class itself that you want to update
user.name = 'Jonny';
user.age = 18;
});
// an alternative way of update the user variable:
user(User(name: 'João', age: 35));

// on view:
Obx(()=> Text("Name ${user.value.name}: Age: ${user.value.age}"))
// you can also access the model values without the .value:
user().name; // notice that is the user variable, not the class (variable has lowercase u)