【发布时间】:2020-03-15 08:25:08
【问题描述】:
我的 APIService 类 中有一个名为 checkAuth() 的函数,它检查我的 SharedPreferences 中是否有令牌。如果有令牌,则返回 AuthenticatedState,否则返回 NotAuthenticatedState。运行下面的代码在开始时没有任何 AuthenticationState。所以我尝试在种子中添加 checkAuth() ,但它会抛出一个错误,即 StreamAuthenticationState> 无法分配给 AuthenticationState。
如何将 Stream<AuthenticationState> 转换为 AuthenticationState?
BehaviorSubject<AuthenticationState> _authStatus =
BehaviorSubject<AuthenticationState>();
Stream<AuthenticationState> get loginStream => _authStatus;
submit() async {
final String validEmail = _email.value;
final String validPassword = _password.value;
APIService.login(validEmail, validPassword)
.then((onValue) {
if (onValue is Success) {
_authStatus.add(AuthenticatedState());
} else {
_authStatus.add(NotAuthenticatedState());
}
});
}
这是用于用户界面的
return StreamBuilder(
stream: stream.loginStream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container(
width: double.infinity,
height: double.infinity,
color: Theme.of(context).cardColor,
child: Center(
child: CircularProgressIndicator(
valueColor: const AlwaysStoppedAnimation(Colors.white),
),
),
);
}
if (snapshot.hasError || snapshot.data is NotAuthenticatedState) {
return Login();
}
if (snapshot.data is AuthenticatedState) {
return App();
}
return Container(width: 0, height: 0);
},
);
它不会在屏幕上显示任何东西,因为它在 start 时没有值,我想是的......
【问题讨论】: