如何将Stream <T>转换为仅返回T?

时间:2019-11-19 18:17:16

标签: flutter dart rxdart

我的 APIService类中有一个名为 checkAuth()的函数,该函数检查我的SharedPreferences中是否存在令牌。如果有令牌,则返回 AuthenticatedState ,否则返回 NotAuthenticatedState 。运行下面的代码开始时没有任何 AuthenticationState 。因此我尝试在种子中添加 checkAuth(),但它引发了一个错误,即流<{AuthenticationState>无法分配给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);
      },
    );

它没有在屏幕上显示任何东西,因为它在开始时没有值,我想是...

1 个答案:

答案 0 :(得分:1)

我认为您必须使用StreamBuilder来获取Stream << strong> T >的 T ,因为这会花费时间,因此读取数据需要花费一些时间与SharedPreferences

StreamBuilder<T>(    /// T represent the type of fetched data, Assuming it's String
    stream: /// put the stream var in there or function with stream as a return
    builder:(BuildContext context, AsyncSnapshot<T> snapshot){
        if(snapshot.hasData) /// Check If it finishes fetching the data
            retrun Text( snapshot.data ); /// snapshot.data variable store the data that fetched
    }
);

查看此页面更多形式:

https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html

///更新答案

您必须使用以下命令初始化SharedPreferences上的数据:


SharedPreferences.getInstance().then((SharedPreferences sp) {
      bool _testValue = sharedPreferences.getBool(spKey);
      // will be null if never previously saved
      if (_testValue == null) {
        _testValue = false;
        // set an initial value
      }
    });