简体   繁体   中英

flutter - async function always returns null, while it is not null

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM