无法使用其官方API获取技术部分的nytimes数据



我正在尝试使用nytimes api来获取技术新闻部分并在我的web应用程序上使用它,但_articles.length抛出了noSuchMethodError的错误,我尝试运行它与体育和其他部分,它工作,但它抛出了技术部分的错误,我只想要我的项目,我也尝试了邮差的url它在那里的技术工作得很好,但不是在扑动和dart请帮助,

我得到以下错误在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

我不知道为什么它抛出这个null错误这是我的dart文件,我在最后几行代码检查

下面使用了长度函数。
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 TimesnTop 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();
}
}
}

在上面的代码中,无论条件如何,只有circularprogressindicator()在执行。我从youtube上下载了这个教程

这是我的文章模型类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'],
);
}
}

这很可能导致你的错误:

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

确保它不为空。当你在一个列表上调用一个操作方法(比如foreach)时,你得到的错误就会产生,因为dart会先检查它的长度,如果列表为空,你就会得到错误。

在调用。length: 之前检查它是否为null,这应该可以解决你的问题。
if(_articles != null) 
_articles.length > 0 
?  _buildArticlesGrid(mediaQuery)
:  Center(
child: CircularProgressIndicator(),),

相关内容

  • 没有找到相关文章

最新更新