我试图保存在缓存中的文章,我通过上面的链接API服务的代码提取,但我得到了一个错误,在搜索图标的FutureBuilder搜索主页中的文章,告诉我“参数类型'未来〈ArticleModel?〉'不能被分配给参数类型'未来?'”谁能给予我一个手,找出这个问题?谢谢你提前
产品型号
class ArticleModel with ChangeNotifier{
int id;
String? urlImage;
String? urlImageSource;
String? title;
final String? description;
ArticleModel({
required this.id,
required this.urlImage,
required this.urlImageSource,
required this.title,
required this.description,
});
factory ArticleModel.fromJson(Map<String, dynamic> parsedJson) => ArticleModel(
id: parsedJson["id"],
urlImage: parsedJson["_embedded"]["wp:featuredmedia"][0]["link"],
urlImageSource: parsedJson["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["thumbnail"]["source_url"],
title: parsedJson["title"]["rendered"].replaceAll("’", "'").replaceAll("<p>", "").replaceAll("</p>", ""),
description: parsedJson['content']['rendered'],
);
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['urlImage'] = urlImage;
data['urlImageSource'] = urlImageSource;
data['title'] = title;
data['desciption'] = description;
//date:['urlImage'] != null ? ['urlImage'].toString().replaceFirst('https:', 'urlImageSource') : null;
return data;
}
}
链接API服务
class ApiNewsPage {
final String url = newsJsonLink; // Link news
Future<ArticleModel?> getNewsArticles() async {
String nameDB = "articledata.json";
var dir = await getTemporaryDirectory();
File file = File(dir.path + "/" + nameDB);
if(file.existsSync()) {
print("Loading Articles from cache");
var jsonData = file.readAsStringSync();
ArticleModel response = ArticleModel.fromJson(json.decode(jsonData));
return response;
} else {
print("Fetching articles from API internet");
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var jsonArticle = response.body;
ArticleModel res = ArticleModel.fromJson(json.decode(jsonArticle));
/// save json in local file
file.writeAsStringSync(jsonArticle, flush: true, mode: FileMode.write);
return res;
}
}
}
}
文章的FutureBuilder搜索图标
actions: <Widget>[
/// First search icon
FutureBuilder<List>(
future: categoryNews.getNewsArticles(),
builder: (context, snapshot) { // AsyncSnapshot
if (snapshot == null || !snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
return IconButton(
icon: const Icon(Icons.search, color: Colors.white,),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context)=> SearchBar(posts: _posts,)
));
},
);
}
return IconButton(
icon: const Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SearchBar(
posts: snapshot.data!,
),
),
);
},
);
}),
],```
2条答案
按热度按时间brccelvz1#
请尝试以下代码:
uujelgoq2#
您使用了FutureBuilder的泛型,但您的函数返回了Future〈ArticleModel?〉类型。我不知道ArticleModel类是如何声明的,但据我所知,您必须在此模型中有一个文章列表。请从snapshot.date inse FutureBuilder获取它