Reputation: 1830
I am using Bloc architect for my project. I am trying to use a function from my Bloc file in the Ui of my app, and send a form to server and use the response. but when I make the call it returns null. while the response is not null in other parts of my app(i.e repo etc.) here is the code of my Ui:
MaterialButton(
color: Colors.deepPurple,
minWidth: screenAwareSize(500, context),
onPressed: () {
_submitForm(authBloc, user, pass);
},
void _submitForm(AuthBloc authBloc, String user, String pass) async {
formKey.currentState.save();
if (formKey.currentState.validate()) {
var response = await authBloc.login(user, pass);
//when I print(response) it shows null
}
}
here is my bloc class:
class AuthBloc extends MainBloc {
final Repo _repo = Repo();
PublishSubject<Future<UserModel>> _authController = new PublishSubject<Future<UserModel>>();
Observable<Future<UserModel>> get auth => _authController.stream;
login(String user, String pass) async {
Future<UserModel> item = await _repo.login(user, pass);
_authController.sink.add(item);
}
dispose() {
_authController.close();
}
}
AuthBloc authBloc = new AuthBloc();
and here is my API class:
class API{
Future<UserModel> login(String user, String pass) async {
var response =
await client.get(base_url + "login.php?user=${user}&pass=${pass}");
return UserModel.fromJSON(json.decode(response.body));
}}
here is my repo class:
class Repo {
final API api = new API();
login(String user, String pass) async => await api.login(user, pass);}
Upvotes: 0
Views: 1731
Reputation: 341
Your function login(String user, String pass)
does not seems to return anything. By default, it will return Future<void>
. That's why your response is null.
The easiest way to fix this is to return item in your login function as follow.
Future<UserModel> login(String user, String pass) async {
return _repo.login(user, pass);
}
Although, this might work. I don't think this is the proper of using Bloc architecture in the Rx way.
You may consider using FutureBuilder
or StreamBuilder
in your view.
And convert your auth
to type of Future<UserModel>
. And make your view subscribe to changes in AuthBloc
.
Upvotes: 1