【问题标题】:Not able to Fetch nytimes data for Technology Section using their official API无法使用其官方 API 获取技术部分的 nytimes 数据
【发布时间】:2021-11-13 01:29:38
【问题描述】:

我正在尝试使用 nytimes api 获取技术新闻部分并在我的网络应用程序上使用它,但 _articles.length 向我抛出了 noSuchMethodError 的错误对于技术部分,我只希望在我的项目中使用它,我也尝试过邮递员上的 url,它适用于那里的技术,但不适用于颤振和飞镖,请帮助,

我在使用技术部分的 vscode 控制台中遇到错误,

Error: NoSuchMethodError: 'length'
method not found
Receiver: null
Arguments: []
    at Object.throw_ [as throw] (http://localhost:60362/dart_sdk.js:5061:11)
    at api_service.APIService.new.fetchArticlesBySection (http://localhost:60362/packages/devcom/services/api_service.dart.lib.js:43:23)
    at fetchArticlesBySection.next (<anonymous>)
    at http://localhost:60362/dart_sdk.js:38640:33
    at _RootZone.runUnary (http://localhost:60362/dart_sdk.js:38511:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:60362/dart_sdk.js:33713:29)
    at handleValueCallback (http://localhost:60362/dart_sdk.js:34265:49)
    at Function._propagateToListeners (http://localhost:60362/dart_sdk.js:34303:17)
    at _Future.new.[_completeWithValue] (http://localhost:60362/dart_sdk.js:34151:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:60362/dart_sdk.js:34172:35)
    at Object._microtaskLoop (http://localhost:60362/dart_sdk.js:38778:13)
    at _startMicrotaskLoop (http://localhost:60362/dart_sdk.js:38784:13)
    at http://localhost:60362/dart_sdk.js:34519:9

我不知道它为什么会抛出这个空错误 这是我的飞镖文件,我在下面的最后几行代码检查中使用了长度函数

import 'package:devcom/models/article_model.dart';
import 'package:devcom/services/api_service.dart';
import 'package:flutter/material.dart';
import 'package:devcom/utils/responsive.dart';
import 'package:url_launcher/url_launcher.dart';

class ExploreSection extends StatefulWidget {
  @override
  _ExploreSectionState createState() => _ExploreSectionState();
}

class _ExploreSectionState extends State<ExploreSection> {
  List<Article> _articles = [];

  @override
  void initState() {
    super.initState();
    _fetchArticles();
  }

  _fetchArticles() async {
    List<Article> articles =
        await APIService().fetchArticlesBySection("technology");
    setState(() {
      _articles = articles;
    });
  }

  _buildArticlesGrid(MediaQueryData mediaQuery) {
    List<GridTile> tiles = [];
    _articles.forEach((article) {
      tiles.add(_buildArticleTile(article, mediaQuery));
    });
    return Padding(
      padding: responsivePadding(mediaQuery),
      child: GridView.count(
        crossAxisCount: responsiveNumGridTiles(mediaQuery),
        mainAxisSpacing: 30.0,
        crossAxisSpacing: 30.0,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        children: tiles,
      ),
    );
  }

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  _buildArticleTile(Article article, MediaQueryData mediaQuery) {
    return GridTile(
      child: GestureDetector(
        onTap: () => _launchURL(article.url),
        child: Column(
          children: <Widget>[
            Container(
              height: responsiveImageHeight(mediaQuery),
              alignment: Alignment.bottomCenter,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.0),
                  topRight: Radius.circular(20.0),
                ),
                image: DecorationImage(
                  image: NetworkImage(article.imageUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(10.0),
              alignment: Alignment.center,
              height: responsiveTitleHeight(mediaQuery),
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20.0),
                  bottomRight: Radius.circular(20.0),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black12,
                    offset: Offset(0, 1),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Text(
                article.title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    return Scaffold(
      body: ListView(
        children: <Widget>[
          SizedBox(height: 80.0),
          Center(
            child: Text(
              'The New York Times\nTop Tech Articles',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 30.0,
                fontWeight: FontWeight.bold,
                letterSpacing: 1.5,
              ),
            ),
          ),
          SizedBox(height: 15.0),
          if (_articles.length > 0)         // the error causing line is this ig 
            _buildArticlesGrid(mediaQuery)
          else
            Center(
              child: CircularProgressIndicator(),
            ),
        ],
      ),
    );
  }
}

这是我的api_service.dart:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:devcom/models/article_model.dart';

class APIService {
  final String _baseUrl = 'api.nytimes.com';
  static const String API_KEY = 'MY_API_KEY_HERE';

  Future<List<Article>> fetchArticlesBySection(String section) async {
    Map<String, String> parameters = {
      'api-key': API_KEY,
    };
    Uri uri = Uri.https(
      _baseUrl,
      "/svc/topstories/v2/$section.json",
      parameters,
    );
    try {
      var response = await http.get(uri);
      Map<String, dynamic> data = json.decode(response.body);
      List<Article> articles = [];
      data['results'].forEach(
        (articleMap) => articles.add(Article.fromMap(articleMap)),
      );
      return articles;
    } catch (err) {
      throw err.toString();
    }
  }
}

在上面的代码中,只有 CirclularProgressIndicator() 正在执行,而与条件无关。 我已经从 youtube source

学习了本教程

这是我的文章模型类 dart 文件:

class Article {
  final String title;
  final String byline;
  final String url;
  final String imageUrl;
  final String publishedDate;
  final String summary;

  Article({
    required this.title,
    required this.byline,
    required this.url,
    required this.imageUrl,
    required this.publishedDate,
    required this.summary,
  });

  factory Article.fromMap(Map<String, dynamic> map) {
    return Article(
      title: map['title'],
      byline: map['byline'],
      url: map['url'],
      imageUrl: map['multimedia'].length > 0
          ? map['multimedia'][3]['url']
          : 'https://images.unsplash.com/photo-1504711434969-e33886168f5c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80',
      publishedDate: map['published_date'],
      summary: map['abstract'],
    );
  }
}

【问题讨论】:

  • 你可以在控制台打印长度吗?
  • @AmitSingh OP 将得到完全相同的错误。
  • @AmitSingh 首先我尝试在它抛出的脚手架中打印_articles.length > 此表达式的类型为“void”,因此无法使用其值。尝试检查您是否使用了正确的 API;可能有一个函数或调用会返回您没想到的 void。还要检查也可能是无效的类型参数和变量。所以我尝试使用 print outside scaffold 和 buildcontext 但这也没有打印任何其他我应该尝试的东西

标签: flutter api web-services dart webservice-client


【解决方案1】:

这很可能导致您的错误:

 List<Article> articles =
        await APIService().fetchArticlesBySection("technology");

确保它不为空。每当您在列表上调用操作\方法时都会产生您遇到的错误,例如 foreach,因为 dart 首先检查它的长度,如果列表为空,则会收到错误。

不过,这应该可以解决您的问题,方法是在 call.length 之前检查它是否为空:

if(_articles != null) 
    _articles.length > 0 
       ?  _buildArticlesGrid(mediaQuery)
       :  Center(
       child: CircularProgressIndicator(),),

【讨论】:

  • 我尝试使用您的代码向我展示操作数不能为空,因此条件始终为真。删除条件。但这并没有改变任何东西,它只是像往常一样显示 CircularProgressIndicator 任何其他解决方案先生,
  • 如果你得到了循环指示符,这意味着你的错误已经消失了。而且你的清单是空的。
  • 确保您的列表不为空。
  • 是的,它现在可以工作了,谢谢我通过使用另一个部分而不是技术来检查它
  • 嘿,但我无法与技术部分合作,这不仅仅是获取问题所在,你能帮助其他部分吗?我尝试使用体育和艺术部分。实际上我的使用这个 nytimes api 的主要座右铭是获取技术部分的新闻,但只有这不起作用,请你帮忙
猜你喜欢
  • 1970-01-01
  • 2019-07-24
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多