gpt4 book ai didi

Flutter - 未处理的异常 : type 'String' is not a subtype of type 'int' of 'index'

转载 作者:行者123 更新时间:2023-12-03 02:50:29 29 4
gpt4 key购买 nike

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

E/flutter ( 9292): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'



模型.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 数据未显示在我创建的 View 中。

我做错了什么?

任何建议都会有所帮助。

最佳答案

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

    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();
});
}

}

关于Flutter - 未处理的异常 : type 'String' is not a subtype of type 'int' of 'index' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543318/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com