Future in setter

I'm new to dart and I'm trying to run an existing project, but it shows the error below in this code snippet:

The return type of getter 'loggedUserName' is 'Future' which isn't assignable to the type 'String' of its setter 'loggedUserName'. Try changing the types so that they are compatible.dart(getter_not_assignable_setter_types)

 static Future<String> get loggedUserName async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(LOGGED_USERNAME_KEY);
  }

 static set loggedUserName(String userName) {
    SharedPreferences.getInstance().then((prefs) => prefs.setString(LOGGED_USERNAME_KEY, userName));
  }

Upvotes: 0

Views: 210

Answers (1)

Dabbel
Dabbel

Reputation: 2825

Instantiate SharedPreferences only once in the constructor (or some init method) of the class.

Use this instance within the setter/getter methods. The initialization should be done by the time the setter/getter methods are called.

(If needed, check for prefs == null inside these methods and handle a delay accordingly.)

Something along these lines:

  static late final prefs;

  // call this method to initialze preferences
  yourInit() async {
    prefs = await SharedPreferences.getInstance();
  }

  static String? get loggedUserName {
    return prefs.getString(LOGGED_USERNAME_KEY); // may be null
  }

  static set loggedUserName(String userName) {
    prefs.setString(LOGGED_USERNAME_KEY, userName);
  }

You may want to get rid of all thestatics, but that depends on how you plan to to setup your class.

Documentation

https://pub.dev/packages/shared_preferences

Upvotes: 1

Related Questions