3

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?:/

pb4now
  • 1,305
  • 4
  • 18
  • 45
  • can you show the content of "User.fromJson" method and User class – rosh-dev851 Oct 02 '21 at 17:22
  • You have a corresponding setter that takes `User` instead of `User?`, and the types of a getter and setter are expected to match. See https://dart.dev/tools/diagnostic-messages#getter_not_subtype_setter_types and https://groups.google.com/a/dartlang.org/g/misc/c/74VgbBxVXoM?pli=1. – jamesdlin Oct 02 '21 at 17:55

1 Answers1

2

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

Janux
  • 841
  • 1
  • 9
  • 19