How Use shared preference with injectable and get_it in flutter?

江枫思渺然 提交于 2021-02-09 08:59:12

问题


im using injectable and get_it package in flutter i have a shared preference class :

@LazySingleton()
class SharedPref {
  final String _token = 'token';
  SharedPreferences _pref;

  SharedPref(this._pref);

  Future<String> getToken() async {
    return _pref.getString(_token) ?? '';
  }

  Future<void> setToken(String token) async {
    await _pref.setString(_token, token);
  }
}

this class inject as LazySingleton and i have a module for inject the shared preference :

@module
abstract class InjectableModule {

 @lazySingleton
 Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}

in bloc class im using SharedPref class :

@injectable
class LoginCheckBloc extends Bloc<LoginCheckEvent, LoginCheckState> {
  final SharedPref sharedPref;

  LoginCheckBloc({@required this.sharedPref}) : super(const LoginCheckState.initial());

  @override
  Stream<LoginCheckState> mapEventToState(
    LoginCheckEvent event,
  ) async* {
    if (event is CheckLogin) {
      final String token = await sharedPref.getToken();
      if (token.isEmpty){
        yield const LoginCheckState.notLogin();
      }else{
        yield const LoginCheckState.successLogin();
      }
    }
  }
}

when i use LoginCheckBloc with getIt<> i have an error for injecting the shared prefrence :

BlocProvider<LoginCheckBloc>(
          create: (BuildContext context) => getIt<LoginCheckBloc>()..add(CheckLogin()),
        ),

the error message is :

You tried to access an instance of SharedPreferences that was not ready yet
'package:get_it/get_it_impl.dart':
Failed assertion: line 272 pos 14: 'instanceFactory.isReady'

how use shared preference with injectable ??


回答1:


It worked on mine when I used @preResolve the SharedPreference

@module
abstract class InjectableModule{

@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}

and then on the injectable class you write this

final GetIt getIt = GetIt.instance;

@injectableInit
Future<void> configureInjection(String env) async {
await $initGetIt(getIt, environment: env);
}

and on the main class

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureInjection(Environment.prod);
runApp(MyApp());
}



回答2:


I was able to solve it by wrapping runApp() with GetIt.I.isReady<SharedPreferences>().

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  GetIt.I.isReady<SharedPreferences>().then((_) {
    runApp(MyApp());
  });
}


来源:https://stackoverflow.com/questions/62978048/how-use-shared-preference-with-injectable-and-get-it-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!