【发布时间】:2020-04-19 22:28:50
【问题描述】:
我正在尝试获取 api,我可以在控制台中打印 api 响应。但是,当我收到对我的模型类的响应时,控制台会显示类似这样的错误
E/flutter (9292): [错误:flutter/lib/ui/ui_dart_state.cc(157)] 未处理的异常:“String”类型不是“int”类型的子类型 '索引'
model.dart
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.dart
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数据格式吗?