Flutter-getx, widget does not re-render when RxMap set to a new value

Issue

I’m building a widget that renders based on the contents of an RxMap. I start with the RxMap initialized to empty, and upon clicking a button set the RxMap to contain a new value. After setting the new value for the RxMap, the widget does not re-render to display the new map values.

Here’s my code:

(EDIT: included all the boilerplate as well to prevent confusion. Each class is in a separate file with relevant imports in all the other files.)

class MyController extends GetxController {
  var selectedItem = {}.obs;
}

class MyBinding extends Bindings {
  @override
  void dependencies() {
    Get.put(MyController());
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext highContext) {
    return GetMaterialApp(
      title: 'App',
      getPages: [
        GetPage(
            name: "/test", 
            page: () => MyClass(),
            binding: MyBinding()),
      ],
      initialRoute: "/test",
    );
  }
}

final saController = Get.find<MyController>();

class MyClass extends StatelessWidget {
  
  Widget build(context) {
    print(saController.selectedItem);
    return Scaffold(
      child: Column(
        children: [
          Obx(() => Container(
              child: Text(saController.selectedItem.toString())
            )),
          TextButton(
            child: Text("click"),
            onPressed: (() {
              saController.selectedItem = RxMap({"test": "item"});
              saController.selectedItem.refresh();
              saController.update();
              print(saController.selectedItem);
            })
          )
        ]
      )
    );
  }
}

The first print statement correctly prints the empty object to the console and the onPressed print statement correctly prints the new object with its key and value included to the console, but the widget does not re-render with the new value. refresh() and update() don’t appear to do anything.

This seems to be specific to RxMap, I’ve been able to get other datatypes to update on change successfully, e.g. swapping out the RxMap value for a boolean value and toggling it from true to false on click causes the widget to re-render correctly without changing any other parts of the code.

Solution

Your UI will not trigger an update unless the value of a Rx variable (selectedItem.value) is changed. But you are updating the Rx variable (selectedItem) itself.

Therefore,you need to change saController.selectedItem = RxMap({"test": "item"}); to saController.selectedItem.value = {"test": "item"};

  • And I think you don’t actually need to call refresh() and update() anymore.

Answered By – S. M. JAHANGIR

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.