Search code examples
flutter-getx

Flutter getx - using recative list as argument gives imporper use of getx error


I have GetXController with RxList, When I create widget with the list as argument (and this is the only observerable), I get an error

[Get] the improper use of a GetX has been detected. 

The controller looks like this:

class Controller extends GetxController {
  static Controller get to => Get.find();
  final RxList<int> numbers = <int>[].obs;
}

And the usage is like this:

class ShowWidget extends StatelessWidget {
  ShowWidget({Key? key}) : super(key: key);
  final Controller c = Controller.to;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300,
      width: 300,
      color: Colors.red,
      child: (Obx(
        () => ItemsList(numbers: c.numbers),
      )),
    );
  }
}

If I add the list length as argument, it seems to work ok, but I'm trying to understand if why this is not working.

Full example is here https://pastebin.com/WrQqqsPx

Thanks for any help.


Solution

  • Although lists are Rx by default (thus don't require .value to call/do operations), but in case of observing them on observer widgets (Obx,GetX) you either have to access their elements or invoke/call any methods/properties. Because until you do so, they are still the Rx references (Like Stream). They will only be observed when their actual value is used. This is much like the boxed/un-awaited Future.

    Therefore, you can do something like this:

    Obx(() => ItemsList(numbers: c.numbers.toList())),
    

    Or:

    Obx(() => ItemsList(numbers: c.numbers.call())),
    

    I prefer calling .toList() though.