Home > OS >  null safety issue for getter with if-statment
null safety issue for getter with if-statment

Time:10-03

I'm trying to retrive User data from sharedPreferances with code:

User? get user {
    String? u = sharedPreferences.getString("user");

    if (u == null) {
       return null;
    } else {
       return User.fromJson(jsonDecode(u));
    }
}

but I'm getting error "The return type of getter 'user' is 'User?' which isn't a subtype of the type 'User' of its setter 'user'."

I want to be able to return null but compiler just doesn not allow me because of null safety.

Can someone tell me what I'm missing here?:/

CodePudding user response:

I suppose the type of your setter is User which is not nullable, but your getter is User? which is nullable, i.e. the types are different. And the compiler insists that the setter and getter should have the same type.

class User {
  
}

class Foo {
  
  set user(User user) {
    
  }
  
  User? get user {
    return null;
  }
}

So, the fix is to use both for the setter and the getter a nullable or a not nullable type.

  set user(User? user) {
    
  }
  
  User? get user {
    return null;
  }

Try it on Dartpad

  • Related