Search code examples
flutterflutter-getx

How to not initialise variable in GetxController from getX library in Flutter


In GetXcontroller, I need one variable named isOK that must not be initialised, because it's used to determine the selection of a widget, and I don't want any selection when app is opened.

When the variable is initialised, I can write that

color: c.isOK.value ? AppTheme.selected: Colors.transparent

But when it's not with var isOK = Rx<Bool>; c.isOK.value is red underlined with the error: "The getter 'value' isn't defined for the type 'Type'".

And with var isOk = Bool().obs;, the error is "Conditions must have a static type of 'bool'"

Have you any solution to encounter the problem. I thought about a local state variable to manage the selection and save it as global variable, but I'd like to do it with only global variable. Thanks


Solution

  • to use GetX Observables you need to define them as:

    var isOK = true.obs;
    //       OR
    var isOK = RxBool(true);
    

    This will automatically give it the type of RxBool.

    For your case you need to initialise your variable as RxnBool. This observable can store three values: True, False and Null. You can pass a check in your widget tree then show the desired.

    You can initialise the RxnBool as:

    var isOK = RxnBool(null);
    

    Assigning the value to the variable whenever required is same as RxBool.

    isOK.value = false;
    isOK.value = true;
    isOK.value = null;
    

    Apart from this if you do not want to use GetX you can always use a nullable and check if value is null or not then initialise it later before use;

    Bool? someVar = null;