James Maddinson
James Maddinson

Reputation: 33

How do I return to the user stream in flutter

I'm having an issue return a Stream to a StreamBuilder widget in a flutter. I'm trying to access a custom class that is stored token.

class User {
  String token;
  User({this.token});
}
===============================

class AuthService {
  String url = 'https://reqres.in/api/login';
  String token = '';
// {
//   "email": "[email protected]",
//   "password": "cityslicka"
// }
  Map data;
  Future signIn(String email, String password) async {
    final response =
        await post(url, body: {'email': email, 'password': password});
    data = jsonDecode(response.body);
    print(data['token']);
    token = data['token'];
    _userFromDatabaseUser(data);
    return data;
  }
  //create user obj based on the database user
  User _userFromDatabaseUser(Map user) {
    return user != null ? User(token: user['token']) : null;
  }
  //user stream for provider
  Stream<User> get user {
    return  .................. ;
  }

Upvotes: 3

Views: 7690

Answers (2)

nvoigt
nvoigt

Reputation: 77304

You could use a stream controller:

class AuthService {
  final String url = 'https://reqres.in/api/login';
  final controller = StreamController<User>();

  Future<User> signIn(String email, String password) async {
    final response = await post(url, body: {'email': email, 'password': password});
    final data = jsonDecode(response.body);
    final user = _userFromDatabaseUser(data);
    controller.add(user);
    return user;
  }

  //create user obj based on the database user
  User _userFromDatabaseUser(Map user) {
    return user != null ? User(token: user['token']) : null;
  }

  //user stream for provider
  Stream<User> get user {
    return controller.stream;
  }

Please note that this approach is a simplistic example that has some flaws, you should read up on it in the documentation.

If you use this for the purpose you describe, you may want to look into the pattern and it's implementation as . It might seem easier to do the user in this way by hand, but once you reach the point where you have multiple of those streams, you may want a more structured approach.

Upvotes: 3

Johny Saini
Johny Saini

Reputation: 909

You can use  
Stream<User> get user async*{
yield  .................. ;
}

you can use yield keyword when you want to return stream object.

2nd way you can use a stream controller. You can add value in controller and
listen wherever you want to listen in your app there is no need to return stream

Upvotes: 0

Related Questions