颤振 - 未处理异常:类型 'String' 不是类型 'int' 的子类型 'index'



我正在尝试获取api,我可以在控制台中打印api响应。但是,当我收到对我的模型类的响应时,控制台显示并出现这样的错误

E/颤振 ( 9292(: [错误:颤振/lib/ui/ui_dart_state.cc(157(] 未处理的异常:"字符串"类型不是类型"int"的子类型 "索引">

模型.飞镖

class CategoryDishes {
final String dishId;
final String dishName;
final String dishDescription;
CategoryDishes(
{this.dishId,
this.dishName,
this.dishDescription,});
factory CategoryDishes.fromJson(Map<String, dynamic> json) {
return CategoryDishes(
dishId: json['dish_id'],
dishName: json['dish_name'],
dishDescription: json['dish_description'],
}
static Resource<List<CategoryDishes>> get all {
return Resource(
url: Constants.FOOD_API_URL,
parse: (response) {
final result = json.decode(response.body.toString());
print(response);
Iterable list = result['category_dishes'];
return list.map((model) => CategoryDishes.fromJson(model)).toList();
});
}
}

web_service.飞镖

class Resource<T> {
final String url;
T Function(Response response) parse;
Resource({this.url, this.parse});
}
class Webservice {
Future<T> load<T>(Resource<T> resource) async {
final response = await http.get(resource.url);
if (response.statusCode == 200) {
debugPrint("----D------>" + response.body);
return resource.parse(response);
} else {
throw Exception('Failed to load data!');
}
}
}

debugPrint在控制台中显示 api,但也显示上述错误,并且 api 数据未显示在我创建的视图中。

我做错了什么?

任何建议都会有所帮助。

返回 JSON 数组的 API !尝试如下!

static Resource<List<CategoryDishes>> get all {
return Resource(
url: Constants.FOOD_API_URL,
parse: (response) {
final result = json.decode(response.body.toString());
print(response);
//added 0 indexex, so it gets 1st element of JSON Arrays
Iterable list = result[0]['table_menu_list'][0]['category_dishes'];
return list.map((model) => CategoryDishes.fromJson(model)).toList();
});
}
}

当 API 返回我们不能使用的数组时

result['category_dishes'] 

相反,我们直接使用结果,因为它是一个列表

List list= result ;
list.map((i) =>.....

我得到了同样的错误,这就是我的解决方案。

我从 firebase 收到此错误,因为我没有将字段值放在引号中。它们必须放在引号中才能正常工作。

products.json?auth=token&orderBy=CreatorID <- Error

只需将字段值放在引号中即可

products.json?auth=token&orderBy="CreatorID" <- Resolved

最新更新