【问题标题】:how to convert Stream<T> to return only T?如何将 Stream<T> 转换为仅返回 T?
【发布时间】:2020-03-15 08:25:08
【问题描述】:

我的 APIService 类 中有一个名为 checkAuth() 的函数,它检查我的 SharedPreferences 中是否有令牌。如果有令牌,则返回 AuthenticatedState,否则返回 NotAuthenticatedState。运行下面的代码在开始时没有任何 AuthenticationState。所以我尝试在种子中添加 checkAuth() ,但它会抛出一个错误,即 StreamAuthenticationState> 无法分配给 AuthenticationState

如何将 Stream&lt;AuthenticationState&gt; 转换为 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 时没有值,我想是的......

【问题讨论】:

    标签: flutter dart rxdart


    【解决方案1】:

    我认为您必须使用StreamBuilder才能从StreamT中获取T,由于时间成本,使用@读取数据需要一些时间987654323@.

    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
          }
        });
    

    【讨论】:

    • 第一次打开是否收到空值?
    • 它显示一个空白屏幕,因为 snapshot.hasdata 是假的
    • 检查 SharedPreferences 的初始值。
    • 如果我打印 checkAuth() 的返回值,它返回 NotAuthenticatedState
    • 返回AppLogin 类是什么意思?你的意思是推送新的小部件吗?
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多