我正在尝试使用网络调用实现一个简单的新闻订阅应用程序,在屏幕上以列表视图显示最新的故事。目前的代码可以从API获取响应(因为我在日志中看到了整个响应主体),但似乎无法在UI中显示数据,出现以下错误:
类型_InternalLinkedHashMap<String, dynamic>不是类型List的子类型
这是JSON结构
{
"response": {
"status": "ok",
"userTier": "developer",
"total": 25095,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 2510,
"orderBy": "relevance",
"results": [
{
"id": "australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
"type": "article",
"sectionId": "australia-news",
"sectionName": "Australia news",
"webPublicationDate": "2018-08-12T18:00:08Z",
"webTitle": "Energy policy hangs in balance, as Senate debates euthanasia",
"webUrl": "https://www.theguardian.com/australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
"apiUrl": "https://content.guardianapis.com/australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
"isHosted": false,
"pillarId": "pillar/news",
"pillarName": "News"
}, {
"id": "media/2018/jun/13/the-rev-colin-morris-obituary-letter",
"type": "article",
"sectionId": "media",
我的理解是,我想先在列表中显示 webTitle
,等我清楚了网络概念后再添加其他字段,但是遇到上面提到的错误。这是我的完整代码:
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Network Example',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new Scaffold(
appBar: AppBar(
title: new Text('Network Example'),
),
body: new Container(
child: new FutureBuilder<List<News>> (
future: fetchNews(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(snapshot.data[index].newsTitle,
style: new TextStyle(
fontWeight: FontWeight.bold)
),
new Divider()
],
);
}
);
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
),
),
);
}
Future<List<News>> fetchNews() async {
final response = await http.get('https://content.guardianapis.com/search?q=debates&api-key=');
print(response.body);
List responseJson = json.decode(response.body.toString());
List<News> newsTitle = createNewsList(responseJson);
return newsTitle;
}
List<News> createNewsList(List data) {
List<News> list = new List();
for (int i = 0; i< data.length; i++) {
String title = data[i]['webTitle'];
News news = new News(
newsTitle: title);
list.add(news);
}
return list;
}
}
class News {
final String newsTitle;
News({this.newsTitle});
factory News.fromJson(Map<String, dynamic> json) {
return new News(
newsTitle: json['webTitle'],
);
}
}
我之前查看了类似的问题,并阅读了JSON数据结构的文章,但似乎无法解决这个问题。
.cast<int>();
这样的内容? - Darshanint.parse(myString)
- Shady Azizahttps://stackoverflow.com/q/56524623/1830228
谢谢。 - DolDurma