Dubey sai vithal teja
Dubey sai vithal teja

Reputation: 43

how to convert Stream<T> to return only T?

I have a function named checkAuth() in my APIService class which checks whether there is token in my SharedPreferences. if there is a token it returns AuthenticatedState or else it returns NotAuthenticatedState. Running the below code doesn't have any AuthenticationState at the start. so I tried to add the checkAuth() in the seeded but it throws an error that Stream<AuthenticationState> can't be assigned to AuthenticationState.

How can I convert Stream<AuthenticationState> to 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());
      }
    });
  }

This is for UI

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

It doesn't display any thing on the screen because it doesn't have a value at start , I think so ...

Upvotes: 0

Views: 81

Answers (1)

Muhammad Hasan Alasady
Muhammad Hasan Alasady

Reputation: 130

I think you have to user StreamBuilder to get T form Stream<T>, because of the time cost, It's take a time when read data with 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
    }
);

Check this page form more:

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

/// Update answer

You have to initial the data on SharedPreferences with:


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

Upvotes: 1

Related Questions