首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flutter:为什么我在使用斩波器的api调用中只得到了3个结果?

Flutter:为什么我在使用斩波器的api调用中只得到了3个结果?
EN

Stack Overflow用户
提问于 2021-02-19 14:24:17
回答 1查看 99关注 0票数 0

当调用这个接口时,我使用chopper只能得到3个结果,但是当我使用普通的http包时,我得到了更多的结果

我的斩波服务文件和我已经生成了*.chopper.dart文件

代码语言:javascript
复制
import 'package:chopper/chopper.dart';

part 'chopper_api_service.chopper.dart';

@ChopperApi(baseUrl: 'https://newsapi.org/v2')
abstract class ChopperApiService extends ChopperService {
  @Get(path: '/top-headlines')
  Future<Response> getNews({
    @Query('apiKey') String apiKey = 'secret',
    @Query('category') String category = 'health',
    @Query('country') String country = 'in'
  });

  static ChopperApiService create() {
    final client = ChopperClient(
      baseUrl: 'https://newsapi.org/v2',
      services: [
        _$ChopperApiService(),
      ],
      converter: JsonConverter(),
    );
    return _$ChopperApiService(client);
  }
}

在我试图得到结果的UI中,

代码语言:javascript
复制
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chopper/chopper.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import '../../../constants/url.dart';
import '../models/chopper_api_service.dart';


class ChopperNewsCard extends StatefulWidget {
  @override
  _ChopperNewsCardState createState() => _ChopperNewsCardState();
}

class _ChopperNewsCardState extends State<ChopperNewsCard> {
  ChopperApiService chopperApiService;
  Future<Response> apiResponse;
  @override
  void initState() {
    super.initState();
    chopperApiService = ChopperApiService.create();
    apiResponse = chopperApiService.getNews();
  }

  @override
  Widget build(BuildContext context) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;

    return FutureBuilder<Response>(
      future: apiResponse,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final news = jsonDecode(snapshot.data.bodyString);
          print(news);  //<-----printing it
          return Container(
            height: height * 0.37,
            width: double.infinity,
            child: ListView.builder(
              itemCount: news.length,
              physics: AlwaysScrollableScrollPhysics(),
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return Container(
                  width: width * 0.70,
                  padding: EdgeInsets.only(right: width * 0.05),
                  child: Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15),
                    ),
                    elevation: 3,
                    child: Column(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(15),
                          child: CachedNetworkImage(
                            imageUrl:
                                news['articles'][index]['urlToImage'] == null
                                    ? Url.noImage
                                    : news['articles'][index]['urlToImage'],//<--- this 
                            fit: BoxFit.cover,
                            width: double.infinity,
                            height: height * 0.2,
                            placeholder: (context, url) =>
                                Center(child: CircularProgressIndicator()),
                            errorWidget: (context, url, error) =>
                                Icon(Icons.error_outline_sharp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(
                              right: width * 0.03,
                              left: width * 0.03,
                              top: width * 0.03),
                          child: Text(
                            news['articles'][index]['title'],
                            maxLines: 4,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          );
        } else {
          return Center(
              child: Lottie.asset('assets/lottie/loading.json',
                  height: width * 0.5, width: width * 0.5),);
        }
      },
    );
  }
}

当打印时,它也只显示3结果,但在totalResults类别中,它显示70

代码语言:javascript
复制
{status: ok, totalResults: 70, articles: [{source: {id: null, name: Deseret News}, author: Herb Scribner, title: Why COVID symptoms still appears if you take zinc, vitamin c - Deseret News, description: Do vitamin C and zinc help fight off COVID-19? A new sutdy says that’s not the case., url: https://www.deseret.com/u-s-world/2021/2/18/22288048/covid-19-symptoms-zinc-vitamin-c, urlToImage: https://cdn.vox-cdn.com/thumbor/6Vl9l5InMVmP9-Oqu_WVvgcThYw=/0x147:2510x1461/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/22294628/AP20357531088811.jpg, publishedAt: 2021-02-19T04:00:00Z, content: A new study suggests that vitamin C and zinc dont help fight off COVID-19, even when theyre taken at high doses.
Whats going on?
The study published in mid-February in JAMA Network Open found that … [+1522 chars]}, {source: {id: google-news, name: Google News}, author: null, title: Sask. health-care worker dies after positive COVID-19 test - CBC News: The National, description: null, url:<…>

现在,我是否需要在查询参数中添加某些内容以获得更多结果

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-19 14:41:36

默认情况下,newsapi每页显示20个结果。您可以通过使用pageSizepage参数来控制它。

Top headlines documentation

print(news);的输出有限,不会打印整个地图。

使用以下打印语句检查articles列表中有多少个对象:print('Articles count: ${news['articles'].length}');

您需要更改此代码才能获得商品数量:

代码语言:javascript
复制
  child: ListView.builder(
              itemCount: news['articles'].length,
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66272677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档