【发布时间】:2021-11-07 00:46:42
【问题描述】:
我正在尝试从 newsApi 获取数据,但我似乎收到了上述错误。 包括的是我的 main.dart 代码
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Article>> fetchArticles(http.Client client) async {
//final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/Articles'));
String link = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=MykEYhere";
final response = await client.get(Uri.parse(link));
// Use the compute function to run parseArticles in a separate isolate.
return compute(parseArticles, response.body);
}
// A function that converts a response body into a List<Article>.
List<Article> parseArticles(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Article>((json) => Article.fromJson(json)).toList();
}
class Article {
final String author;
final String title;
final String description;
final String url;
final String urlToImage;
final String content;
const Article({
required this.author,
required this.title,
required this.description,
required this.url,
required this.urlToImage,
required this.content
});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
author: json['author'],
title: json['title'],
description: json['description'],
url: json['url'],
urlToImage: json['urlToImage'],
content: json['content'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
const appTitle = 'NewApi Trial';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Article>>(
future: fetchArticles(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('An error has occurred! ${snapshot.error}'),
);
} else if (snapshot.hasData) {
return ArticlesList(articles: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class ArticlesList extends StatelessWidget {
const ArticlesList({Key? key, required this.articles}) : super(key: key);
final List<Article> articles;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
return ClipRect(
child: Column(
children: [
Image.network(articles[index].urlToImage),
Text(articles[index].title)
],
),
);
//Image.network(Articles[index].thumbnailUrl);
},
);
} }
下面是运行代码后出现的错误
NoSuchMethodError: Class '_InternalLinkedHashMap
我们将不胜感激您的帮助
【问题讨论】:
标签: json flutter flutter-futurebuilder