如何在flutter中将可共享的首选项与injectable和get_it一起使用? [英] How Use shared preference with injectable and get_it in flutter?

查看:275
本文介绍了如何在flutter中将可共享的首选项与injectable和get_it一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im在flutter中使用Injectable和get_it包我有一个共享的偏好设置类:

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);
  }
}

该类作为 LazySingleton 注入,并且我有一个模块用于注入共享首选项:

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

在bloc类中,使用SharedPref类:

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

当我将LoginCheckBloc与getIt<>一起使用时我在注入共享首选项时出错:

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

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

错误消息是:

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 ??

推荐答案

当我使用 @preResolve 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);
}

在主班上

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

这篇关于如何在flutter中将可共享的首选项与injectable和get_it一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆