I'm trying to understand how to use the GetX package in a Flutter application to get a reactive update in a Text widget when the value is changed in a TextFormField. What is displayed in the Text widget is the property of an observable object. And it is that property that is updated from the TextFormField. The value is correctly updated in the controller but not in the widget. If I use a string variable directly, it does update correctly. But as soon as I'm using an object, it does not update anymore.

This is a really simple sample of my application, just to be sure that that basics are understood.

Here is my code:

class User {
  String name = "";
}

class TestController extends GetxController {
  TestController();

  final user = User().obs;
}

class MyHomePage extends StatelessWidget {
  final c = Get.put(TestController());
  final String title;
  MyHomePage({this.title});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Container(
          width: Get.width * 0.8,
          height: Get.height * 0.8,
          child: Column(
            children: [
              Obx(() => Text(c.user.value.name)),
              TextFormField(
                onChanged: (value) => c.user.value.name = value,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Many thanks for your help !

2

There are 2 answers

1
daseed On

Ok I found the solution thanks to the CodeX youtuber.

To be able to update reactively the UI when you change the value of a property an object, even if this object is set as observable, you need to have the property observable as well.

So the correct code will look like this

class User {
  final name = "".obs;
}

class TestController extends GetxController {
  TestController();

  final user = User().obs;
}

class MyHomePage extends StatelessWidget {
  final c = Get.put(TestController());
  final String title;
  MyHomePage({this.title});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Container(
          width: Get.width * 0.8,
          height: Get.height * 0.8,
          child: Column(
            children: [
              Obx(() => Text(c.user.value.name.value)),
              TextFormField(
                onChanged: (value) => c.user.value.name.value = value,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
0
Kaushik Kakdey On

Update Your onChanged() fn to this

Obx(() => Text(c.user.value.name)),
TextFormField(onChanged: (value) {
  c.user.value.name = value;
  c.user.refresh();
}),