Search code examples
flutterdartflutter-getx

Flutter Getx: initial value of obs variable set to null


Upon now I always use getx observable declarations like this:

var someString = ''.obs;
var someNumber = 0.obs;

and so on...

But what if some variables don't have an initial value at first, and I actually want them to be null and later change them?


Solution

  • For non null-safe (pre Dart 2.12), you can declare your observable variables like this:

    final someVariable = Rx<Type>();
    

    For example:

    final someString = Rx<String>();
    final someNumber = Rx<int>();
    

    And for null-safety (Dart 2.12 or later), Just use Rxn<Type> instead of Rx<Type>.

    For example:

    final someString = Rxn<String>();
    final someNumber = Rxn<int>();