Flutter Getx: initial value of obs variable set to null

Viewed 9984

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?

3 Answers

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>();

If you don't have an initial value for your [Rx] value (at the first time), you need to use

final Rx<YourObject?> yourObject = (null as YourObject?).obs;

Or for more organizing your code, you can create a separate class, like this

class RxNullable<T> {
  Rx<T> setNull() => (null as T).obs;
}

and use:

final Rx<YourObject?> yourObject = RxNullable<YourObject?>().setNull()

If anyone else does face this problem.

final Rx<YourObject?> yourObject = (null as YourObject?).obs;

will work.

but if there's any message that says "Unnecessary cast. Try removing the cast.", just add this comment

// ignore: unnecessary_cast

above the line, and then save.

Related