我想知道是否有人可以帮助我进行身份验证。我收到间歇性错误。我的应用程序中的路由基本上取决于从 newUser
返回的 SharedPreferences
。在代码中,返回的状态取决于 _mapAuthenticationUserChangedToState
中的逻辑。但是,有时事件不会“足够快”地从 SP 读取并且路由错误。即使路由有效......我可以从应用程序的日志中看到,即使路由是正确的,它不应该路由到的屏幕的 initState
被调用。我的代码中是否有任何明显的错误。 ..(也可能写到 SP 不够快,我是我的社交登录流程)
class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> {
AuthenticationBloc({
@required AuthenticationRepository authenticationRepository,
}) : assert(authenticationRepository != null),
_authenticationRepository = authenticationRepository,
super(const AuthenticationState.unknown()) {
_userSubscription = _authenticationRepository.user.listen(
(user) => add(AuthenticationUserChanged(user, user.isNewUser)),
);
}
final AuthenticationRepository _authenticationRepository;
StreamSubscription<PraxUser> _userSubscription;
@override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
if (event is AuthenticationUserChanged) {
var userRepository = UserRepository();
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isNewUser = prefs.getBool('is_new_user') ?? false;
yield _mapAuthenticationUserChangedToState(event, isNewUser);
} else if (event is AuthenticationLogoutRequested) {
unawaited(_authenticationRepository.logOut());
}
}
@override
Future<void> close() {
_userSubscription?.cancel();
return super.close();
}
AuthenticationState _mapAuthenticationUserChangedToState(
AuthenticationUserChanged event,
bool isNewUser,
) {
if (event.user != PraxUser.empty) {
if (isNewUser) {
return AuthenticationState.signedUp(event.user);
} else {
return AuthenticationState.authenticated(event.user);
}
} else {
return AuthenticationState.unauthenticated();
}
}
}
编辑:
else if (state is SignUpSuccess) {
Navigator.of(context).popUntil((route) => route.isFirst);
BlocProvider.of<AuthenticationBloc>(context).add(AuthenticationUserChanged(state.user, true));
} else if (state is AlreadySignedUpSuccess) {
Navigator.of(context).popUntil((route) => route.isFirst);
BlocProvider.of<AuthenticationBloc>(context).add(AuthenticationUserChanged(state.user, false));
编辑:
我的 main.dart 有一个监听器
return BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
final id = state.user.id;
switch (state.status) {
case AuthenticationStatus.signedUp:
_navigator.pushNamedAndRemoveUntil<void>(
AppRouter.onboarding,
(route) => false,
);
break;
case AuthenticationStatus.authenticated:
_navigator.pushNamedAndRemoveUntil<void>(
AppRouter.home,
(route) => false,
);
break;
case AuthenticationStatus.unauthenticated:
_navigator.pushNamedAndRemoveUntil<void>(
AppRouter.intro,
(route) => false,
);
break;
default:
break;
}