Search code examples
flutter

How to fix this issue of can't be accessed using static?


Error:

Instance member 'initSharedPreferences' can't be accessed using static access.dartstatic_access_to_instance_member

class SharedPrefHelper {
  SharedPreferences? sharedPref;

  Future<void> initSharedPreferences() async {
    print("Running get instance");
    sharedPref = await SharedPreferences.getInstance();
  }
}

Future initiateAuthBloc() async {
    await SharedPrefHelper.initSharedPreferences(); 
  }

when I tried to access this methos got an above error, How to fix it?


Solution

  • You have to define static before variable, Like this

      class SharedPrefHelper {
      static SharedPreferences? sharedPref;
    
      static Future<void> initSharedPreferences() async {
        print("Running get instance");
        sharedPref = await SharedPreferences.getInstance();
      }
    }
    
    Future<void> initiateAuthBloc() async {
      await SharedPrefHelper.initSharedPreferences();
    }