如何在flutter中将共享首选项与可注入和get_it一起使用?

时间:2020-07-19 08:42:22

标签: flutter dependency-injection sharedpreferences flutter-dependencies injectable

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

@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 注入,并且我有一个模块用于注入共享首选项:

@module
abstract class InjectableModule {

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

在bloc类中,使用SharedPref类:

@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 <>一起使用时,我在注入共享首选项时出错:

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'

如何将共享首选项与可注射??一起使用?

2 个答案:

答案 0 :(得分:6)

我能够用runApp()包装GetIt.I.isReady<SharedPreferences>()来解决这个问题。

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

答案 1 :(得分:6)

当我使用@preResolve SharedPreference

时,它对我有效
@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());
}