我试图从JSON API获取数据到我的flutter移动的应用程序,但失败了。
我想我的model.dart
文件有问题。
下面是我的model.dart
代码
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
Future<List<Book>> fetchBooks(http.Client client) async {
final response =
await client.get('https://boimarket.abirahsan.com/public/api/v1/books');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseBooks, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Book> parseBooks(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Book>((json) => Book.fromJson(json)).toList();
}
class Book {
final String name;
final String author;
final String genreClass;
final String imgUrl;
final String pdf;
final int category;
Book({
this.name,
this.author,
this.genreClass,
this.imgUrl,
this.pdf,
this.category,
});
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
name: json['name'] as String,
imgUrl: json['image'] as String,
pdf: json['pdf'] as String,
author: json['author'] as String,
genreClass: json['genre_class'] as String,
category: json['category'] as int,
);
}
}
字符串
这是我的输出图像:
的数据
问题出在哪里?我该怎么弥补?
1条答案
按热度按时间ao218c7q1#
用给定函数替换
parseBooks
函数。cast
方法采用<RK,RV>()而不是Map<Rv,RK>()。编译后的代码还告诉用<String,dynamic>()替换<Map<String,dynamic>()。你可以在https://api.dart.dev/stable/2.8.4/dart-core/Map/cast.html这里阅读更多关于强制转换方法的信息。您也可以使用
as
关键字代替cast
方法。个字符