Home > database >  The getter 'isNull' was called on null
The getter 'isNull' was called on null

Time:11-10

I am using getx and getstorage package while executing following flutter code. I want to check if a variable is null, however I get following error. Variable named variable is not stored on disk while executing below code.

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'isNull' was called on null. Receiver: null Tried calling: isNull)

screen.dart

TextButton(
  onPressed: () {
    var _variable =  userStorage.read('variable');
    print('_variable = $_variable'); 
    // above prints _variable = null
    if(_variable.isNull){
      // do something if its null
      // but results in flutter error
    }
    else{
      // do something else
    }
  },
  child: Obx(() => (Text(
    'variable value=' controller.variable.value,
  )
  )
  )
)

controller.dart

class Controller extends GetxController {
  var userStorage = GetStorage();
}

CodePudding user response:

Use default value if it's null

var _variable =  userStorage.read('variable') ?? "notSet";
if(_variable == "notSet"){
  // do something 
}
else{
  // do something else
}
  • Related