_CastError(类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型转换中类型 'List<dynamic>' 的子



想再问一次。。。尝试实现存储在本地数据库中的数据API。。。JSON API的形式其中有JSON数组的对象。。。要将数据从API加载到本地数据库时出错。。。大致来说,这是一个错误,因为"错误的模型或什么

Api服务

class MealApiProvider {
Future<List<Categories>> getAllMeal() async {
var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
Response response = await Dio().get(url);
print("Hasil Respon ${response.data}");
return (response.data as List).map((employee) {
print('Inserting $employee');
DBProvider.db.insertMeals(Categories.fromJson(employee));
}).toList();
}
}

型号

class DataMeal {
final List<Categories> categories;
DataMeal({this.categories});
@override
String toString() {
return 'DataMeal{categories: $categories}';
}
factory DataMeal.fromJson(Map<String, dynamic> json) {
return DataMeal(
categories: List<Categories>.from(
json["categories"].map(
(categories) {
return Categories.fromJson(categories);
},
),
),
);
}
Map<String, dynamic> toJson() => {
"categories": List<dynamic>.from(
categories.map(
(x) => x.toJson(),
),
),
};
}

本地数据库

initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
final String path = join(documentsDirectory.path, '$nameDatabase');
print('insert database $path');
return await openDatabase(path, version: 1, onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute('CREATE TABLE $nameTable('
'idCategory,'
'strCategory TEXT,'
'strCategoryThumb TEXT,'
'strCategoryDescription TEXT'
')');
});
}
insertMeals(DataMeal newMeal) async {
await deleteAllMeal();
final Database db = await database;
final res = await db.insert("$nameTable", newMeal.toJson());
print("inserting data $res");
return res;
}

错误

return(response.data as List(.map((employee(

响应数据

您的响应一开始就包含map!试试这个

class MealApiProvider {
Future<List<Categories>> getAllMeal() async {
var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
Response response = await Dio().get(url);
print("Hasil Respon ${response.data}");
//***Change below line****
return (response.data['categories'] as List).map((employee) {
print('Inserting $employee');
DBProvider.db.insertMeals(Categories.fromJson(employee));
}).toList();
}
}

而不是

class MealApiProvider {
Future<List<Categories>> getAllMeal() async {
var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
Response response = await Dio().get(url);
print("Hasil Respon ${response.data}");
//*** I change the below line !
return (response.data as List).map((employee) {
print('Inserting $employee');
DBProvider.db.insertMeals(Categories.fromJson(employee));
}).toList();
}
}

相关内容

  • 没有找到相关文章

最新更新