Reputation: 610
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?
Upvotes: 31
Views: 25820
Reputation: 1615
If you do it on class say a station class the code example is
late Rx<Station?> station = Rx<Station?>(null);
Upvotes: 3
Reputation: 1111
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!;
Upvotes: -1
Reputation: 89
Getx in flutter, I search lot of time How class as observable
so fixed, Like this ,
Rx<HomeModel?> mainModel =HomeModel(content: []).obs;
Upvotes: 0
Reputation: 225
You can declare your observable variables like this for (dart 2.18 and above):
Rx varName = (T()).obs;
Upvotes: 0
Reputation: 678
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.
Upvotes: 3
Reputation: 107
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()
Upvotes: 9
Reputation: 5020
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>();
Upvotes: 87