API 数据不显示在屏幕上,仅显示在控制台中

问题描述 投票:0回答:2

我想要做的是在 flutter 应用程序内的卡片上显示 API 数据(书名和评论 URL)。它是纽约时报 API,我想显示所有斯蒂芬·金书评。这一切都被打印到控制台中,但屏幕上没有发生任何事情。当我单击按钮时,它只会被打印,但我希望数据显示在屏幕上的卡片中。请帮忙,这是代码:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

//outsource the class BookReview for OOP
class BookReview extends StatefulWidget {
  static const apiKey = 'jH8F2A1FCudwGV8udVAU4YSLLEr8vqxT';
  static const apiURL =
      'https://api.nytimes.com/svc/books/v3/reviews.json?author=Stephen+King&api-key=$apiKey';

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

class _BookReviewState extends State<BookReview> {
  @override
  void initState() {
    super.initState();
    getBookData();
  }

  Card bookCard;

  var bookNum = List.generate(66, (i) => i);

  Future<Card> getBookData() async {
    http.Response response = await http.get(BookReview.apiURL);

    if (response.statusCode == 200) {
      var decodedData = jsonDecode(response.body);

      for (int book in bookNum) {
        String bookTitle = decodedData['results'][book]['book_title'];
        String reviewURL = decodedData['results'][book]['url'];

        print(bookTitle + ' ' + reviewURL);
      }

      return Card(
          color: Colors.red,
          child: Column(
            children: [],
          ));
    } else {
      print(response.statusCode);
      throw ('there is an error with the status code');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stephen King NYT Reviews'),
      ),
      body: Column(
        children: [
          FlatButton(
            onPressed: () async {
              final Card tmpBookCard = await getBookData();
              setState(() {
                bookCard = tmpBookCard;
              });
            },
            child: Icon(
              Icons.picture_as_pdf,
              size: 50.0,
            ),
          ),
        ],
      ),
    );
  }
}
java ios flutter dart
2个回答
0
投票

您没有在构建函数中使用 bookCard 小部件。例如,您应该在 FlatButton Widget 顶部使用 bookCard。

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stephen King NYT Reviews'),
      ),
      body: Column(
        children: [
          bookCard,
          FlatButton(
            onPressed: () async {
              final Card tmpBookCard = await getBookData();
              setState(() {
                bookCard = tmpBookCard;
              });
            },
            child: Icon(
              Icons.picture_as_pdf,
              size: 50.0,
            ),
          ),
        ],
      ),
    );
  }

0
投票

我看不到你在哪里定义了你的 bookCard,而且在 getBookData() 中,你没有将你获得的数据插入到你返回的卡中

© www.soinside.com 2019 - 2024. All rights reserved.