无法获取JSON API数据

v6ylcynt  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(108)

我试图从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,
    );
  }
}

字符串
这是我的输出图像:


的数据
问题出在哪里?我该怎么弥补?

ao218c7q

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方法。

final parsed = jsonDecode(responseBody) as Map<String, dynamic>;

个字符

相关问题