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

Issue

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.

Answered By – Abbas Jafari

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *