How do I return to the user stream in flutter
2,981
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 bloc pattern and it's implementation as flutter-bloc. 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.
Author by
James Maddinson
Updated on December 23, 2022Comments
-
James Maddinson over 1 year
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 .................. ; }
-
James Maddinson almost 3 yearsI didn't get any value in a wrapper class. what should I do @nvoigt ` class Wrapper extends StatelessWidget { @override Widget build(BuildContext context) { final user = Provider.of<User>(context); print(user); if (user == null) { return Authenticate(); } else { return Home(); } } }`