【发布时间】: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。还要检查也可能是无效的类型参数和变量。所以我尝试使用 printoutside scaffold和buildcontext但这也没有打印任何其他我应该尝试的东西
标签: flutter api web-services dart webservice-client