【问题标题】:Function has a return type of 'Future<String>' but doesn't end with a return statement函数的返回类型为“Future<String>”,但不以 return 语句结尾
【发布时间】:2019-05-09 14:23:54
【问题描述】:

我正在用 Dart (flutter) 编写一个 Future 方法。它只是在 Firebase 上运行查询并返回结果。但即使在编写业务逻辑之前,我也会收到一条警告消息:

[dart] 这个函数的返回类型是'Future',但是 不以 return 语句结束。 [missing_return]

下面是我的 Future 函数:

Future<String> getLikeCount(documentID) async {
    Firestore.instance.collection('favorites').where(documentID).getDocuments().then((data){
      return 'test';
    });  
  }

我对为什么会发生错误有了基本的了解,我假设因为里面有一个“then”,所以在它发生之前,函数什么都不返回。如何克服这个问题?

【问题讨论】:

    标签: firebase dart flutter google-cloud-firestore


    【解决方案1】:

    使用await 而不是then 因为你的方法是async

     final snapshot = await Firestore.instance.collection('favorites').where(documentID).getDocuments();
     return "test";
    

    改变这个:

     _getLikes() async
    

    到这里:

     Future<String> _getLikes() async  
    

    因为您期望String Future

    【讨论】:

    • 正确。但是在运行时我仍然有以下错误:类型'Future'不是'String'类型的子类型
    • _getLikes() async { var likes = await ArticleServices().getLikeCount(widget.post.documentID); return likes; } 仅供参考,这就是我调用函数的方式
    • 将 var likes 更改为 String likes
    • 不走运。运行时仍然有警告消息:'Future' is not a subtype of type 'String'
    • getLikeCount 的返回类型是什么? ,你的方法 getLikeCount 是异步的吗?
    【解决方案2】:

    在没有异步的情况下试试这个

    Future<String> getLikeCount(documentID) {
        return Firestore.instance.collection('favorites').where(documentID).getDocuments().then((data){
          return 'test';
        });  
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多