skip to Main Content

I am learning getx and here i am facing a problem

I hve created a userModel with name and age field and showing on screen

when i tap on elevated button i am changing any name and it should be refresh as i have wrapped text widget into Obx but still not working…Whats the reason?

class UserModel
{
  String name;
  String age;
  UserModel({required this.name,required this.age});

  static UserModel empty()=>UserModel(name: '', age: '');
}

class UserController extends GetxController
{
  Rx<UserModel> loggedUser=UserModel.empty().obs;


  void changeName(String name)
  {
    loggedUser.value.name=name;
   
  }

}

this is screen code

 Widget build(BuildContext context) {
    final controller=Get.put(UserController());
    return SafeArea(
      child: Scaffold(
        body: Obx(() {
          return Column(

          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment:MainAxisAlignment.center,
          children: [

             Text('Name :'+controller.loggedUser.value.name),
            SizedBox(height: 20,),
             Text('Age: '+controller.loggedUser.value.age),
            SizedBox(height: 20,),
            ElevatedButton(onPressed: (){
            controller.changeName('xyz');
            }, child: const Text('Change')),

            Spacer(),
          ],);
        }),
      ),
    );
  }

2

Answers


  1. It has been a while since I last used GetX, but if I recall correctly when declaring the UserModel instance as Rx<UserModel> loggedUser = UserModel.empty().obs, you will need to update the entire UserModel instance, not just its properties.

    Use loggedUser.value = newUser instead of loggedUser.value.name = name.

    If you still want to use loggedUser.value.name=name, consider modifying the UserModel as shown below:

    class UserModel
    {
      final RxString name;
      final RxString age;
      UserModel({required this.name,required this.age});
    
      factory UserModel.empty() => UserModel(name: ''.obs, age: ''.obs);
    }
    

    Good luck and happy coding!

    Login or Signup to reply.
  2. you have set loggedUser as obs and its targetting entire object to be obs

    so you need to update entire object

    and if you are updating only one or few properties of object you need to call refresh method after updating properties..

    so implement your coding as below in your changeName method

    void changeName(String name)
      {
        loggedUser.value.name=name;
    //above code...you are updating a property not entire object
    
    
        loggedUser.refresh();// add this line to your code to refresh entire object
    
       
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search