Flutter:无法获取json API数据

时间:2020-07-27 12:43:50

标签: json api flutter fetch

我正在尝试从json API提取数据到移动的移动应用程序。但是我失败了。

我认为我的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,
    );
  }
}

这是我的输出图像

enter image description here

问题出在哪里?而我该如何解决?

1 个答案:

答案 0 :(得分:0)

用给定的函数替换parseBooks函数。 cast方法采用()而不是Map ()。编译器还告诉将cast >()替换为cast ()。 您可以在https://api.dart.dev/stable/2.8.4/dart-core/Map/cast.html上了解有关强制转换方法的更多信息。

您也可以使用as关键字代替cast方法。

final parsed = jsonDecode(responseBody) as Map<String, dynamic>;
List<Book> parseBooks(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<String, dynamic>();
  return parsed['data'].map<Book>((json) => Book.fromJson(json)).toList();
}