flutterservice-locatorflutter-sharedpreference

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'

Session.dart

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

SessionImpl.dart

class SessionImpl extends Session {
  SharedPreferences sharedPref;

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

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

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

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

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

ServiceLocator.dart

final serviceLocator = GetIt.instance;

Future<void> initDependencies() async {
  _initSharedPref();
  _initSession();
}

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

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

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
    [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
  );

  await initDependencies();

  runApp(MyApp());
}

Solution

  • 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();
      _initSession();
    }
    

    After that the object should be registering without problems.