这是我的密码
错误: NoSuchMethodError:类“未来”没有实例获取“长度”
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key : key ) ;
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String urlToImage;
// Future<Article> newslist;
var newslist;
@override
void initState() {
super.initState();
newslist = fetchArticle();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Api calls',
home: Scaffold(
appBar: AppBar(title: Text('Api Calls'),),
body: ListView.builder(
shrinkWrap: true,
itemCount: newslist.length,
itemBuilder: (context, index) {
return Image.network(newslist[index]['urlToImage']);
})
),
);
}
}
class Article {
final String author;
final String title;
final String description;
final String publishedAt;
final String urlToImage;
final String url;
Article({this.author, this.description, this.title, this.publishedAt, this.urlToImage, this.url});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
author : json['author'],
title: json['title'],
description: json['description'],
publishedAt: json['publishedAt'],
url: json['url'],
urlToImage: json['urlToImage']
);
}
}
Future<Article> fetchArticle() async {
var url =
'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';
final response = await http.get(url);
if (response.statusCode == 200) {
return Article.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load Article');
}
}
lutter:抛出以下NoSuchMethodError构建MyApp(脏,状态:_MyAppState#c93f4):颤振:类“未来”没有实例获取“长度”。颤振:接收者:“未来”颤振的实例:尝试调用:长度颤振:颤振:相关的导致错误的小部件是:
颤栗:当异常被抛出时,这是堆栈:(package:flutter/src/widgets/framework.dart:4502:15):#0 Object.noSuchMethod (dart:core-Object.noSuchMethod/object_patch.dart:53:5)颤振:#1 _MyAppState.build (包:api/main.dart:35:35)颤振:#2 StatefulElement.build StatefulElement.build颤振:#3 ComponentElement.performRebuild ComponentElement.performRebuild颤振:#4 StatefulElement。(package:flutter/src/widgets/framework.dart:4675:11)颤振:#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)颤振:#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)颤振:#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)颤振:#8 ComponentElement.mount (包: performRebuild /src/widget/颤振:#9 (package:flutter/src/widgets/framework.dart:3446:14)颤振:#10 Element.updateChild颤振:#11 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16)颤振:#12 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1119:5)颤振:#13 RenderObjectToWidgetAdapter.attachToRenderTree.(package:flutter/src/widgets/binding.dart:1061:17)颤振:#14 (package:flutter/src/widgets/framework.dart:2607:19)颤振:#15 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1060:13)颤振:#16 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:941:7)颤振:#17 WidgetsBinding.scheduleAttachRootWidget。(package:flutter/src/widgets/binding.dart:922:7)颤振:(从类_RawReceivePortImpl、类_Timer、dart:异步和dart:异步补丁中删除11帧)颤振:颤振:
发布于 2020-07-20 04:13:38
您可以复制粘贴,运行下面的完整代码
步骤1:您可以使用bool _isLoading
来控制加载状态。
步骤2:fetchArticle()
返回Future<List<Article>>
而不是Future<Article>
第3步:使用payloadFromJson(response.body)
,您可以看到完整代码中的Payload
类定义
步骤4:当数据准备就绪时,将_isLoading
设置为false
void getData() async {
newslist = await fetchArticle();
setState(() {
_isLoading = false;
});
}
工作演示
全码
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
Payload({
this.status,
this.totalResults,
this.articles,
});
String status;
int totalResults;
List<Article> articles;
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
status: json["status"],
totalResults: json["totalResults"],
articles: List<Article>.from(
json["articles"].map((x) => Article.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"totalResults": totalResults,
"articles": List<dynamic>.from(articles.map((x) => x.toJson())),
};
}
class Article {
Article({
this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content,
});
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
DateTime publishedAt;
String content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
source: Source.fromJson(json["source"]),
author: json["author"],
title: json["title"],
description: json["description"],
url: json["url"],
urlToImage: json["urlToImage"],
publishedAt: DateTime.parse(json["publishedAt"]),
content: json["content"] == null ? null : json["content"],
);
Map<String, dynamic> toJson() => {
"source": source.toJson(),
"author": author,
"title": title,
"description": description,
"url": url,
"urlToImage": urlToImage,
"publishedAt": publishedAt.toIso8601String(),
"content": content == null ? null : content,
};
}
class Source {
Source({
this.id,
this.name,
});
String id;
String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"] == null ? null : json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name,
};
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String urlToImage;
// Future<Article> newslist;
List<Article> newslist;
bool _isLoading = true;
Future<List<Article>> fetchArticle() async {
var url =
'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';
final response = await http.get(url);
if (response.statusCode == 200) {
Payload payload = payloadFromJson(response.body);
return payload.articles;
} else {
throw Exception('Failed to load Article');
}
}
void getData() async {
newslist = await fetchArticle();
setState(() {
_isLoading = false;
});
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
getData();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Api calls',
home: Scaffold(
appBar: AppBar(
title: Text('Api Calls'),
),
body: _isLoading
? Center(child: CircularProgressIndicator())
: ListView.builder(
shrinkWrap: true,
itemCount: newslist.length,
itemBuilder: (context, index) {
return Image.network(newslist[index].urlToImage);
})),
);
}
}
发布于 2020-07-20 04:16:38
已经被其他人做了。但我试着上传代码。
有一些问题。
所以我改了从url那里得到文章。使用'FutureBuilder‘只需构建一个带有文章的列表视图。
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String urlToImage;
Future<List<Article>> newslist;
Future<List<Article>> fetchArticle() async {
var url =
'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';
final response = await http.get(url);
if (response.statusCode == 200) {
var data = json.decode(response.body);
List<Article> listArticle = data["articles"].map<Article>((article) {
return Article.fromJson(article);
}).toList();
return listArticle;
} else {
throw Exception('Failed to load Article');
}
}
@override
void initState() {
super.initState();
newslist = fetchArticle();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Api calls',
home: Scaffold(
appBar: AppBar(
title: Text('Api Calls'),
),
body: FutureBuilder<List<Article>>(
future: newslist,
builder: (context, snapshot) {
if (snapshot.hasData) {
// return Container();
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Image.network(snapshot.data[index].urlToImage);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container();
},
),
),
);
}
Widget _buildBody() {
return Container();
}
}
class Article {
final String author;
final String title;
final String description;
final String publishedAt;
final String urlToImage;
final String url;
Article(
{this.author,
this.description,
this.title,
this.publishedAt,
this.urlToImage,
this.url});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
author: json['author'],
title: json['title'],
description: json['description'],
publishedAt: json['publishedAt'],
url: json['url'],
urlToImage: json['urlToImage']);
}
}
https://stackoverflow.com/questions/62988139
复制相似问题