can't initialized Shared Pref using GetIt in flutter


I want to implement a session management system using Shared Preference in my flutter app. For Dependency injection, I use GetIt library. But when I run the app, it says ‘flutter: Error while creating Session’
‘The following ArgumentError was thrown building Builder(dirty):
Invalid argument (Object of type SharedPreferences is not registered inside GetIt.
Did you forget to pass an instance name?
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;)): SharedPreferences’


abstract class Session {
  void storeLoginInfo(String accessToken);
  bool isUserLoggedIn();
  String getAccessToken();
  void deleteLoginInfo();


class SessionImpl extends Session {
  SharedPreferences sharedPref;

  SessionImpl(SharedPreferences sharedPref) {
    this.sharedPref = sharedPref;

  void storeLoginInfo(String accessToken) {
    sharedPref.setBool('login_status', true);
    sharedPref.setString('access_token', accessToken);

  bool isUserLoggedIn() {
    final isLoggedIn = sharedPref.getBool('login_status') ?? false;
    return isLoggedIn;

  String getAccessToken() {
    return sharedPref.getString('access_token') ?? "";

  void deleteLoginInfo() {
    if (sharedPref.containsKey('login_status')) sharedPref.remove('login_status');
    if (sharedPref.containsKey('access_token')) sharedPref.remove('access_token');


final serviceLocator = GetIt.instance;

Future<void> initDependencies() async {

Future<void> _initSharedPref() async {
  SharedPreferences sharedPref = await SharedPreferences.getInstance();

void _initSession() {
  serviceLocator.registerLazySingleton<Session>(() => SessionImpl(serviceLocator()));


void main() async {
    [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],

  await initDependencies();



It seems the only thing you are missing is to await the _initSharedPref function in the initDependencies function. Like follows:

Future<void> initDependencies() async {
await  _initSharedPref();

After that the object should be registering without problems.

Answered By – croxx5f

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

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