Flutter 如何将共享偏好与可注射性一起使用,并在颤振中获得它?
我使用可注射的,并得到它在颤振包 我有一个共同的偏好类:Flutter 如何将共享偏好与可注射性一起使用,并在颤振中获得它?,flutter,dependency-injection,sharedpreferences,flutter-dependencies,injectable,Flutter,Dependency Injection,Sharedpreferences,Flutter Dependencies,Injectable,我使用可注射的,并得到它在颤振包 我有一个共同的偏好类: @LazySingleton() class SharedPref { final String _token = 'token'; SharedPreferences _pref; SharedPref(this._pref); Future<String> getToken() async { return _pref.getString(_token) ?? ''; } Future
@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);
}
}
如何将共享首选项用于可注射???我可以通过将
runApp()
包装为GetIt.I.isReady()
来解决它
void main(){
WidgetsFlutterBinding.ensureInitialized();
GetIt.I.isReady()然后(){
runApp(MyApp());
});
}
当我使用@preResolve
共享参考时,它对我起作用了
@module
abstract class InjectableModule{
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}
@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();
}
}
}
}
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'
void main() {
WidgetsFlutterBinding.ensureInitialized();
GetIt.I.isReady<SharedPreferences>().then((_) {
runApp(MyApp());
});
}
@module
abstract class InjectableModule{
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}
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());
}