Flutter 如何将流转换为仅返回T?

Flutter 如何将流转换为仅返回T?,flutter,dart,rxdart,Flutter,Dart,Rxdart,我的APIService类中有一个名为checkAuth的函数,用于检查我的SharedReferences中是否有令牌。如果存在令牌,则返回AuthenticatedState,否则返回NotAuthenticatedState。运行以下代码在开始时没有任何AuthenticationState。所以我尝试在种子中添加checkAuth,但它抛出了一个错误,即无法将流分配给AuthenticationState 如何将流转换为AuthenticationState BehaviorSubjec

我的APIService类中有一个名为checkAuth的函数,用于检查我的SharedReferences中是否有令牌。如果存在令牌,则返回AuthenticatedState,否则返回NotAuthenticatedState。运行以下代码在开始时没有任何AuthenticationState。所以我尝试在种子中添加checkAuth,但它抛出了一个错误,即无法将流分配给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());
      }
    });
  }
它不会在屏幕上显示任何内容,因为它在开始时没有值,我想是的…

我认为您必须使用StreamBuilder才能获得t表单流,因为时间成本,使用SharedReference读取数据需要一段时间


您在第一次打开时是否收到空值?它显示一个空白屏幕导致快照。hasdata为False检查SharedReferences初始值。如果我打印checkAuth的返回值,则返回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);
      },
    );
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
    }
);

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