26

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?

BigPP
  • 522
  • 2
  • 8
  • 18

6 Answers6

71

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>();
S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30
10

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()
Mykola Meshkov
  • 126
  • 1
  • 4
2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
motasimfuad
  • 530
  • 4
  • 12
0

You can declare your observable variables like this for (dart 2.18 and above):

Rx varName = (T()).obs;

0

Getx in flutter, I search lot of time How class as observable

so fixed, Like this ,

  Rx<HomeModel?> mainModel =HomeModel(content: []).obs;
RIYAS PULLUR
  • 13
  • 1
  • 4
0

Another Best way is you can make your variable optional

final Rx<YourObject>? yourObject;

then user obs when you declare your variable first time

yourObject.value = yourObject.obs;

and use it by force wrap

var newObject = yourObject!;

amit.flutter
  • 883
  • 9
  • 27