我正在使用Future Builder构建列表视图。我正在从服务器获取响应。我正在得到我所需要的。我正在尝试解决一个错误。错误是当我使用http.get
方法从服务器获取数据时:String data=response.body;
我得到了想要的正确响应并将我解析为String catagoeryId=jsonDecode(data)["data"][i]["_id"];
现在我在解码此json时遇到的问题是我使用for循环在构造函数中传递了此String。但是我必须给出长度来停止循环。我使用的长度是: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 ProductCatagoery {
final String id;
final String thumb;
final String name;
final bool active;
ProductCatagoery(this.id,this.thumb,this.name,this.active);
}
响应为:
{“成功”:真,“数据”:[{“ _ id”:“ 5f13cc94c63abc03522eff41”,“拇指”:“ category / fresh-meat.jpg”,“名称”:“鲜肉”,“有效” :true},{“ _ id”:“ 5f13cc73c63abc03522eff40”,“ thumb”:“ category / fruits-vegetables.jpg”,“ name”:“水果和蔬菜”,“ active”:true},{“ _ id”:“ 5f13cca5c63abc03522eff42“,”拇指“:” category / grocery.jpg“,”名称“:”杂货“,”活动“:true}]}
注意:我只需要String data=response.body;
数据长度。我没有使用地图等。如果在第1、2或第3次迭代后返回产品列表,我也会在列表中显示产品。
答案 0 :(得分:0)
首先,解码收到的响应
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}');
}