0

when I upgrade flutter to 2.15, errors disppay as following:

import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesUtil {
  SharedPreferencesUtil._();

  static SharedPreferencesUtil _instance;
  SharedPreferences sharedPreferences;

  static SharedPreferencesUtil getInstance() {
    if (_instance == null) {
      _instance = SharedPreferencesUtil._();
    }
    return _instance;
  }
}

Error: Non-nullable instance field '_instance' must be initialized. Non-nullable instance field 'sharedPreferences' must be initialized. The non-nullable variable '_instance' must be initialized.

shared_preferences: ^0.5.7+3

I don't know how to fix it

1 Answers1

0

Because you define sharedPreferences variable but you not assign it with a value so the error appear. Try to fix as below:

class SharedPreferencesUtil {
   SharedPreferencesUtil._();

   static SharedPreferencesUtil? _instance;
   SharedPreferences? sharedPreferences;

   static Future<SharedPreferencesUtil?>  getInstance() {
     if (_instance == null) {
       var singleton = SpUtil._();
       await singleton._init();
       _instance = singleton;
   }
   return _instance;
 } 
}

Future _init() async {
  sharedPreferences = await SharedPreferences.getInstance();
}
John Henry
  • 71
  • 3