无法从 API 获取任何数据

Posted

技术标签:

【中文标题】无法从 API 获取任何数据【英文标题】:Couldn't get any data from API 【发布时间】:2020-11-30 23:25:43 【问题描述】:

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

这是我的 model.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(
                                          "লেখকঃ ",
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold),
                                        ),
                                        Flexible(
                                          child: Text(
                                            "$mydata[index].author",
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          "বইয়ের ধরণঃ ",
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold),
                                        ),
                                        Flexible(
                                          child: Text(
                                            "$mydata[index].genreClass",
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  ,
                ),
              );
             else 
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.error_outline),
                  Text("Somthing Went to wrong"),
                ],
              );
            
          ,
        ),
      ),
    );
  

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

【问题讨论】:

您的 api 似乎无法正常工作:boimarket.abirahsan.com’s server IP address could not be found 先检查你的网址兄弟:) @Er1 现在这个网址没问题 @ParthPitroda 请立即查看 @AbirAhsan 它仍然无法正常工作 【参考方案1】:

正如您所注意到的,您的 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

【讨论】:

另外,在您的小部件中,您可能需要更改为常规的FutureBuilder,因为没有流。 哦,它正在工作。但是你解释一下,如果我将未来的 builder 转换为 StreamBuilder 有什么问题? 当您获取事件流时应该使用StreamBuilder - 例如来自网络套接字或类似的事件。您的 HTTPS 获取不会是一个流 - 只是一个结果(书籍列表),所以使用 FutureBuilder

以上是关于无法从 API 获取任何数据的主要内容,如果未能解决你的问题,请参考以下文章

无法使用带有工作 api 的 http.get flutter 获取数据

无法从 h2 获取数据

Android Studio 无法从 API 获取 Json

无法从 JSONDecoder 获取数据,没错,是我编的结构?

从 osx 中的任何应用程序获取选定文本的辅助功能 API 替代方案

Flutter - 无法将所有 json 数据从 api 响应保存到 Iterable List 编辑:(无法从可迭代列表中获取数据)