How to combine the usage of GetX and build_value?

585 views Asked by At

Our app has a lot of provider (https://pub.dev/packages/provider) code which uses built_value (https://pub.dev/packages/built_value) to be able to work with immutable data objects.

Now we want to migrate the whole provider functionality to the state management of GetX (https://pub.dev/packages/get) but I am not clear about how to make these two things work together? GetX-controllers work with Rx-Values which are directly used in the logic part and whenever the value changes ONLY the listener gets notified which subscribed to exactly this value. But how does this work when it is combined with built_value? There the "actual" value is more or less hidden by an internal state which holds the data and can only access it indirect via getters.

So e.g. the actual data for a user only can be accessed in the user getter inside the UserProviderState like in the following example:

abstract class UserProviderState implements Built<UserProviderState, UserProviderStateBuilder> {
  User? get user;
  ...
}

An example for a GetX controller (without using built_value) is:


class LoginController extends GetxController {
  RxString username = ''.obs, password = ''.obs;
  RxBool obscurePassword = true.obs;
  ...
}

It is all a bit more nested when using built_value and some advice how to use it correctly with GetX would be really appreciated. Thanks

1

There are 1 answers

0
Andrey Gritsay On

RxObject notifies a listener when its value changes.
I.e. (from docs):

final name = 'GetX'.obs;` 
// only "updates" the stream, if the value is different from the current one. 
name.value = 'Hey';

As build_value always return a new object you would always get a new value.
So in order to trigger an update of your RxObject you just need to pass a new value to it:

class LoginController extends GetxController {
  final state = UserProviderState().obs;
  ...
  void updateState() {
    state.value = state.value..someProperyOfState = 'new val';
  }
}

If you mean that you want replace UserProviderState with GetxController then, congratulations, you misused built_value and you need to move all those properties from there