【问题标题】:returns Instance of '_Future<List<MODELNAME>>' instead of json返回 '​​_Future<List<MODELNAME>>' 的实例而不是 json
【发布时间】:2021-11-02 02:15:16
【问题描述】:

我有一个以 JSON 格式返回地点列表的 API,它在邮递员上运行良好,但我无法让它在 Flutter 上返回。

这里是返回所有地点的函数

Future<List<PlacesModel>> getAllPlaces() async {
  final Storage _localStorage = window.localStorage;
  List<PlacesModel> allPlaces = [];

  Map<String, String> headers = {
    'Content-type': 'application/json',
    'Authorization': 'Bearer ${_localStorage['token']}'
  };
  final allPlacesURl = Uri.parse("http://localhost:3000/common/getPlaces/0");

  var response = await http.get(allPlacesURl, headers: headers);
  if(response.statusCode == 200)
    {
      final decodee = "[" + response.body +"]";
      List body = json.decode(decodee);
      allPlaces = body.map((e) => PlacesModel.fromJson(e)).toList();
      return allPlaces;
    }
}

但它只返回 Instance of '_Future&lt;List&lt;PlacesModel&gt;&gt;' 而不是实际的 json 列表。

【问题讨论】:

    标签: json flutter api dart


    【解决方案1】:

    在您调用getAllPlaces 的位置之前使用await

    List<PlacesModel> someList = await getAllPlaces();
    

    【讨论】:

    • 我有,现在它说 '[Instance of 'PlacesModel']'
    • 这是您需要的列表。只需从位置模型中输入您想要的参数,例如 idname 或您里面的任何内容。这是因为您的类中没有 to string 方法。然而,这回答了你的问题。
    【解决方案2】:

    替换这个:

    if(response.statusCode == 200)
        {
          final decodee = "[" + response.body +"]";
          List body = json.decode(decodee);
          allPlaces = body.map((e) => PlacesModel.fromJson(e)).toList();
          return allPlaces;
        }
    

    与:

        if(response.statusCode == 200)
        {
          return response.body;
        }
    

    【讨论】:

      【解决方案3】:

      如果您真的想传递 json 列表而不是您定义的 placemodel 列表,请使用以下代码 sn-p 函数调用应该是这样的:

      //function call
      var result = await getAllPlaces();// has the json map required and this can further be processed as a json.
      
      
      //function definition
      Future getAllPlaces() async {
        final Storage _localStorage = window.localStorage;
      
        Map<String, String> headers = {
          'Content-type': 'application/json',
          'Authorization': 'Bearer ${_localStorage['token']}'
        };
        final allPlacesURl = Uri.parse("http://localhost:3000/common/getPlaces/0");
      
        var response = await http.get(allPlacesURl, headers: headers);
        if(response.statusCode == 200)
          {
            return response.body;
          }
        else{
            return null;
          }
      }
      

      【讨论】:

      • 它有以下错误无法从函数“getAllPlaces”返回“String”类型的值,因为它的返回类型为“Future>”
      • 已更新代码sn-p请检查。
      • 如果可能的话,请分享来自 api 的响应。
      猜你喜欢
      • 2021-09-24
      • 2021-11-10
      • 2019-05-31
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      相关资源
      最近更新 更多