Search code examples
flutterdart-null-safetyflutter-sharedpreference

The non-nullable variable '_preferences' must be initialized. Try adding an initializer expression


I am trying to implement a class where i can call SharedPreferences funtions.

import 'package:shared_preferences/shared_preferences.dart';


class UserPreferences {
  static SharedPreferences _preferences;

  static const _keyToken = 'token';

  static Future init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  static Future setToken(String token) async =>
    await _preferences.setString(_keyToken, token);

  static String getToken() => _preferences.getString(_keyToken);

}

But i am getting following error:

The non-nullable variable '_preferences' must be initialized.
Try adding an initializer expression.

Solution

  • You must create an object when you create your variable like below inside the method:

      static Future init() async {
        SharedPreferences _preferences = await SharedPreferences.getInstance();
      }
    

    And for using like the property you can do it like below:

    static SharedPreferences _preferences = SharedPreferences.getInstance();
    

    And when you call this property you can use async/await for this _preferences property on that page.