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
It has been a while since I last used GetX, but if I recall correctly when declaring the
UserModel
instance asRx<UserModel> loggedUser = UserModel.empty().obs
, you will need to update the entireUserModel
instance, not just its properties.Use
loggedUser.value = newUser
instead ofloggedUser.value.name = name
.If you still want to use
loggedUser.value.name=name
, consider modifying theUserModel
as shown below:Good luck and happy coding!
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