无法从API获取任何数据

问题描述

我面临从API获取数据的问题。我认为json API中的“数据”在这里产生了问题。这是我的json API链接:https://boimarket.abirahsan.com/api/v1/categories/1/books

这是我的模型。dart-

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

String base_url = "https://boimarket.abirahsan.com/api/v1/categories/1/books";
Future<Book> fetchBooks() async {
  var response = await http.get(base_url);
  if (response.statusCode == 200) {
    print(response.body);
    return Book.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load Book');
  }
}

class Book {
  final String name;
  final String author;
  final String genreClass;
  final String imgUrl;
  final String pdf;
  final String html;
  final String description;
  final String category;

  Book({
    this.name,this.author,this.genreClass,this.imgUrl,this.description,this.html,this.pdf,this.category,});

  factory Book.fromJson(Map<String,dynamic> json) {
    return Book(
      name: json['name'],imgUrl: json['image'],pdf: json['pdf'],html: json['html'],description: json['description'],author: json['author'],genreClass: json['genre_class'],category: json['category'],);
  }
}

这是我的storybooks.dart-

import 'package:boimarket/booksdescription.dart';
import 'package:boimarket/model/model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:draggable_scrollbar/draggable_scrollbar.dart';

class StoryBooksCategory extends StatefulWidget {
  final ScrollController controller;
  final List<Book> storybooks;
  StoryBooksCategory({Key key,@required this.controller,this.storybooks})
      : super(key: key);

  @override
  _StoryBooksCategoryState createState() => _StoryBooksCategoryState();
}

class _StoryBooksCategoryState extends State<StoryBooksCategory> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var _height = MediaQuery.of(context).size.height;
    var _width = MediaQuery.of(context).size.width;
    final Color _whiteCream = Color.fromRGBO(250,245,228,1);
    final Color _darkBlue = Color.fromRGBO(0,68,69,1);
    return Align(
      alignment: Alignment.topCenter,child: Container(
        width: _width / 1.1,child: StreamBuilder(
          stream: fetchBooks().asStream(),builder: (context,snapshot) {
            if (!snapshot.hasData) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[
                  LinearProgressIndicator(
                    backgroundColor: _whiteCream,),Text("Loading"),],);
            } else if (snapshot.hasData) {
              var mydata = snapshot.data;
              print(mydata.length);
              return DraggableScrollbar.rrect(
                controller: widget.controller,backgroundColor: _darkBlue,child: ListView.builder(
                  controller: widget.controller,scrollDirection: Axis.vertical,itemCount: mydata.length,itemBuilder: (context,index) {
                    return GestureDetector(
                      onTap: () {
                        Route route = MaterialPageRoute(
                          builder: (context) =>
                              BookDescription(storyBooksValue: mydata[index]),);
                        Navigator.push(context,route);
                      },child: Padding(
                        padding: const EdgeInsets.only(
                            left: 10.0,right: 10.0,top: 20.0),child: Container(
                          width: _width / 1.1,height: _height / 4,decoration: BoxDecoration(
                              color: _whiteCream,borderRadius: BorderRadius.all(
                                Radius.circular(5.0),boxShadow: [
                                BoxShadow(
                                  color: Colors.black26,blurRadius: 2,spreadRadius: 2,offset: Offset(2.0,2.0),)
                              ]),child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: <Widget>[
                              Flexible(
                                flex: 4,child: Padding(
                                  padding: const EdgeInsets.all(10.0),child: Card(
                                    elevation: 10.0,child: ClipRRect(
                                      borderRadius: BorderRadius.circular(5.0),child: FadeInImage.assetNetwork(
                                        fadeOutCurve: Curves.easeInCubic,placeholder:
                                            'assets/images/bookshelf.jpg',image: mydata[index].imgUrl == null
                                            ? 'assets/images/bookshelf.jpg'
                                            : mydata[index].imgUrl,fit: BoxFit.cover,Flexible(
                                flex: 6,child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          "বইয়ের নামঃ ",style: TextStyle(
                                              fontWeight: FontWeight.bold),Flexible(
                                          child: Text(
                                            "${mydata[index].name}",overflow: TextOverflow.ellipsis,Row(
                                      children: <Widget>[
                                        Text(
                                          "লেখকঃ ",Flexible(
                                          child: Text(
                                            "${mydata[index].author}",Row(
                                      children: <Widget>[
                                        Text(
                                          "বইয়ের ধরণঃ ",Flexible(
                                          child: Text(
                                            "${mydata[index].genreClass}",);
                  },);
            } else {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                  Icon(Icons.error_outline),Text("Somthing Went to wrong"),);
            }
          },);
  }
}

现在我没有从这里得到任何数据。我的代码中的问题出在哪里?我该如何解决?

解决方法

您已经注意到,您的JSON有一个data标签-包含一堆书(不仅仅是一本书)。由于您获得的书不止一本,因此您需要一本List

Future<List<Book>> fetchBooks() async {
  var response = await http.get(base_url);
  if (response.statusCode == 200) {
    var decoded = json.decode(response.body);
    return decoded['data'].map<Book>((b) => Book.fromJson(b)).toList();
  } else {
    throw Exception('Failed to load Book');
  }
}

您的类别也是整数,因此将Book中的类别更改为:

class Book {
  final String name;
  final String author;
  final String genreClass;
  final String imgUrl;
  final String pdf;
  final String html;
  final String description;
  final int category; //<- this is an int

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...