flutter http包中服务器响应的长度

length of server response in flutter http package

我正在使用未来的构建器来构建列表视图。我从服务器得到响应。我得到的正是我需要的。我正在尝试解决一个错误。错误是当我使用 http.get 方法从服务器获取数据时:String data=response.body; 我得到了我想要的正确响应,并将其解析为 String catagoeryId=jsonDecode(data)["data"][i]["_id"];

现在我在解码时遇到的问题 json 我使用 for 循环在我的构造函数中传递了这个字符串。但我必须给出停止循环的长度。我使用的长度是:data.length。它解码我的 json 响应并传递到我的构造函数中。但是在 json 长度结束后它停止工作并崩溃。我检查了 data.length 的长度,大约是 344。但我只有 3 个对象。这是我用于解析的代码:

Future<List<ProductCatagoery>> getCatagories()async{
http.Response response = await http.get("http://138.68.134.226:3020/api/category/");
 List<ProductCatagoery> products=[];
  String data=response.body;
  for (int i=0;i<=data.length;i++) {
String catagoeryId=jsonDecode(data)["data"][i]["_id"];
String catagoeryThumb=jsonDecode(data)["data"][i]["thumb"];
String catagoeryName=jsonDecode(data)["data"][i]["name"];
bool catagoeryActive=jsonDecode(data)["data"][i]["active"];


print('name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
  ProductCatagoery newUser= 
  ProductCatagoery(catagoeryId,catagoeryThumb,catagoeryName,catagoeryActive);
  products.add(newUser);
  print('added ${newUser.id}');
  print('length is${products.length}');
  print('last length data: ${data.length}');
 } 
   return products;
 }

型号class:

class ProductCatagoery {
final String id;
 final String thumb;
 final String name;
 final bool active;
  ProductCatagoery(this.id,this.thumb,this.name,this.active);
 }

响应是:

{"success":true,"data":[{"_id":"5f13cc94c63abc03522eff41","thumb":"category/fresh-meat.jpg","name":"鲜肉"," active":true},{"_id":"5f13cc73c63abc03522eff40","thumb":"category/fruits-vegetables.jpg","name":"水果和蔬菜","active":true},{"_id" :"5f13cca5c63abc03522eff42","thumb":"category/grocery.jpg","name":"杂货店","active":true}]}

注意:我只需要String data=response.body;数据长度。我没有使用地图等。如果我在第 1、2 或 3 次迭代后 return 产品列表,我也会在列表中显示产品。

首先,对收到的响应进行解码

final responseFormat = json.decode(response.body);

然后,你可以得到你想要循环的列表

final data = responseFormat["data"];

最后,你可以得到列表的长度:data.length

完整代码

List<ProductCatagoery> products = [];
  final responseFormat = json.decode(response.body);
  final data = responseFormat["data"];
  for (int i = 0; i < data.length; i++) {
    String catagoeryId = data[i]["_id"];
    String catagoeryThumb = data[i]["thumb"];
    String catagoeryName = data[i]["name"];
    bool catagoeryActive = data[i]["active"];

    print(
        'name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
    ProductCatagoery newUser = ProductCatagoery(
        catagoeryId, catagoeryThumb, catagoeryName, catagoeryActive);
    products.add(newUser);
    print('added ${newUser.id}');
    print('length is${products.length}');
    print('last length data: ${data.length}');
  }