flutter-异步函数始终返回null,但不为null [英] flutter - async function always returns null, while it is not null

查看:610
本文介绍了flutter-异步函数始终返回null,但不为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为项目使用Bloc Architect。我正在尝试使用应用程序的Ui中Bloc文件中的函数,并将表单发送到服务器并使用响应。但是当我拨打电话时,它返回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(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


    }
  }

这是我的集团课程:

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

这是我的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));
  }}

这是我的回购类别:

 class Repo {
    final API api = new API();
  login(String user, String pass) async => await api.login(user, pass);}


推荐答案

您的函数 login(String user,String pass)似乎未返回任何内容。默认情况下,它将返回 Future< void> 。这就是为什么您的响应为空的原因。

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

虽然,这可能有用。我认为这不是以Rx方式使用Bloc架构的适当方法。

Although, this might work. I don't think this is the proper of using Bloc architecture in the Rx way.

您可以考虑使用 FutureBuilder StreamBuilder
并将您的 auth 转换为 Future< UserModel> 的类型。并让您的视图订阅 AuthBloc 中的更改。

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.

这篇关于flutter-异步函数始终返回null,但不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆