I am newbie to flutter and Bloc architecture and I am trying to use Bloc for my login functionality. I am trying to make a call to a function in my Bloc file, but I do not know how to do that. also I would be glad if you could help me to see if there is any other problems in my use of Bloc. 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);}
I will try to explain first what BLOC components should do as short as possible (and as trivial as possible).
You can have other components too, based on what your app does, like:
Now, I would suggest to use the BLOC pattern with Dependency Injection too, without it is kind of useless. With DI, you can mock all components till UI and it would be very easy to unit test all your code.
Also, I think there's no point to mix RxDart(library) with Streams/Future(dart equivalent of RxDart lib). For start, I would suggest to use only one of it and based on your code snippet, I would suggest to have better look on how to use Rx overall.
So, below you have a small code snippet on how I would use the block patter to do a login(it would be nice to check the code comments too :) ).