【问题标题】:Flutter Future always return nullFlutter Future 总是返回 null
【发布时间】:2019-06-02 10:04:31
【问题描述】:

我的代码有什么问题,它总是返回 null

getLocation().then((r)  {
                          if (r != null) {
                            print("r=" + r.length.toString());
                          } else {
                            print("result is null");
                          } 
                        });



Future< List<double>> getLocation() async {
   // print("getLocation called");
      location = new Location();
    List<double> result=[];

      location.getLocation().then((loc) {

      result.add(loc.latitude);
      result.add(loc.longitude);
      result.add(4213);
      //  print(loc.latitude.toString() + "," + loc.longitude.toString() +"  l="+l1.length.toString());
      return result;

    }).catchError((e){
      return result;
    });
  }

【问题讨论】:

  • 请添加更多细节。

标签: flutter flutter-dependencies


【解决方案1】:

您没有在函数中返回任何内容,仅在您的 then 回调中返回。 由于您无论如何都使用异步语法,因此您可以选择:

Future< List<double>> getLocation() async {
  location = new Location();
  List<double> result=[];

  var loc = await location.getLocation();
  result.add(loc.latitude);
  result.add(loc.longitude);
  result.add(4213);
  return result;
}

我已经从代码中删除了错误处理,但如果你愿意,你可以使用 try-catch。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2020-07-10
    • 1970-01-01
    • 2019-07-31
    • 2021-09-16
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多