简体   繁体   English

Flutter:无法获取 json API 数据

[英]Flutter: Can't fetch json API data

I am trying to fetch data from a json API to my flutter mobile application.我正在尝试从 json API 获取数据到我的 flutter 移动应用程序。 But I failed.但我失败了。

I think I have a problem in my model.dart file.我想我的model.dart文件有问题。

Here is my code for 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,
    );
  }
}

and here is my output Image这是我的 output 图片

在此处输入图像描述

Where is the problem?问题出在哪里? And How can I fix it?我该如何解决?

Replace your parseBooks function with the given function.用给定的 function 替换您的parseBooks function。 The cast method takes <RK, RV>() not Map<Rv,RK>(). cast方法采用 <RK, RV>() 而不是 Map<Rv,RK>()。 The compiled also told to replace cast<Map<String,dynamic>>() with cast<String,dynamic>().编译后还告诉用 cast<String,dynamic>() 替换 cast<Map<String,dynamic>>()。 You can read more about the cast method here https://api.dart.dev/stable/2.8.4/dart-core/Map/cast.html .您可以在此处阅读有关投射方法的更多信息https://api.dart.dev/stable/2.8.4/dart-core/Map/cast.html .

You can also use as keyword instead of cast method.您也可以使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM