简体   繁体   English

flutter-异步函数始终返回null,但不为null

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

I am using Bloc architect for my project. 我正在为我的项目使用Bloc Architect。 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. 我正在尝试使用应用程序Ui中Bloc文件中的函数,并将表单发送到服务器并使用响应。 but when I make the call it returns null. 但是当我拨打电话时,它返回null。 while the response is not null in other parts of my app(ie repo etc.) here is the code of my Ui: 虽然响应在我的应用程序的其他部分(即回购等)中不为空,但这是我的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: 这是我的API类:

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. 您的函数login(String user, String pass)似乎未返回任何内容。 By default, it will return Future<void> . 默认情况下,它将返回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. 我认为这不是以Rx方式使用Bloc架构的合适方法。

You may consider using FutureBuilder or StreamBuilder in your view. 您可以在视图中考虑使用FutureBuilderStreamBuilder And convert your auth to type of Future<UserModel> . 并将您的auth转换为Future<UserModel>类型。 And make your view subscribe to changes in AuthBloc . 并使您的视图订阅AuthBloc更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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