Flutter/dart 将数据格式化为实例无效
Flutter/dart formatting data to instances not working
因此,我可以接收数据并将其打印出来,但它无法再正确格式化为列表。我附上了下面用于获取数据和模型的所有代码。加上打印输出。有人可以帮帮我吗
获取数据
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:world_time/services/model/article_model.dart';
class News {
String? city;
List? articles;
News({this.city});
Future<void> getNews() async {
try {
Response response = await get(Uri.parse('https://newsapi.org/v2/everything?q=$city&from=2021-12-05&sortBy=popularity&apiKey=MY API KEY'));
Map<String, dynamic> json = jsonDecode(response.body);
print(json);
List<dynamic> body = json['articles'];
articles = body.map((dynamic item) => Article.fromJson(item)).toList();
print(articles);
}
catch (e){
print("Caught error: $e");
}
}
}
打印(json)
{status: ok, totalResults: 520, articles: [{source: {id: bbc-news, name: BBC News}, author: null, title: Unstoppable Salah closes in on more records - his year in numbers, description: As Liverpool's Mohamed Salah closes in on another record, BBC Sport takes a statistical look at his superb 2021., url: https://www.bbc.co.uk/sport/football/59646200, urlToImage: https://ichef.bbci.co.uk/live-experience/cps/624/cpsprodpb/1269A/production/_122081457_mohamedsalah.jpg, publishedAt: 2021-12-16T08:49:23Z, content: Mohamed Salah has scored 36 goals in all competitions for Liverpool in 2021
I/flutter ( 2307): "He is phenomenal. For sure, at the moment, he is the best player in the world."
I/flutter ( 2307): Liverpool manager Jurgen Klopp may well … [+5278 chars]}, {source: {id: reuters, name: Reuters}, author: null, title: Man Utd face Villa, Leicester host Watford in FA Cup third round - Reuters, description: Manchester United entertain Aston Villa in the FA Cup third round, while holders Leicester City welcome Watford and West Ham United are at home
打印(文章)
由于 articles 为空,请捕获 returns this
I/flutter ( 2307): Caught error: type 'Null' is not a subtype of type 'String' in type cast
article_model
class Article {
Source? source;
String? author;
String? title;
String? description;
String? url;
String? urlToImage;
String? publishedAt;
String? content;
Article(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'] as String,
title: json['title'] as String,
description: json['description'] as String,
url: json['url'] as String,
urlToImage: json['urlToImage'] as String,
publishedAt: json['publishedAt'] as String,
content: json['content'] as String,
);
}
}
source_model
String? id;
String? name;
Source({this.id, this.name});
factory Source.fromJson(Map<String, dynamic> json) {
return Source(id: json['id'], name: json['name']);
}
}
在您的模型上,所有变量都是 String?
类型,也就是说,变量将是 String
或 null
。但是当你制作模型时,你像这样分配所有变量:variable: json['variable'] as String
,这意味着如果它们是 null
他们会抛出错误,因为你做的是 as String
,而不是 as String?
,这就是错误的来源。
要解决此问题,我相信应该可以完全删除 as String
,如下所示:
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'],
title: json['title'],
description: json['description'],
url: json['url'],
urlToImage: json['urlToImage'],
publishedAt: json['publishedAt'],
content: json['content'],
);
}
上面的方法可能不起作用,如果不起作用,则应该:
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'] as String?,
title: json['title'] as String?,
description: json['description'] as String?,
url: json['url'] as String?,
urlToImage: json['urlToImage'] as String?,
publishedAt: json['publishedAt'] as String?,
content: json['content'] as String?,
);
}
因此,我可以接收数据并将其打印出来,但它无法再正确格式化为列表。我附上了下面用于获取数据和模型的所有代码。加上打印输出。有人可以帮帮我吗
获取数据
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:world_time/services/model/article_model.dart';
class News {
String? city;
List? articles;
News({this.city});
Future<void> getNews() async {
try {
Response response = await get(Uri.parse('https://newsapi.org/v2/everything?q=$city&from=2021-12-05&sortBy=popularity&apiKey=MY API KEY'));
Map<String, dynamic> json = jsonDecode(response.body);
print(json);
List<dynamic> body = json['articles'];
articles = body.map((dynamic item) => Article.fromJson(item)).toList();
print(articles);
}
catch (e){
print("Caught error: $e");
}
}
}
打印(json)
{status: ok, totalResults: 520, articles: [{source: {id: bbc-news, name: BBC News}, author: null, title: Unstoppable Salah closes in on more records - his year in numbers, description: As Liverpool's Mohamed Salah closes in on another record, BBC Sport takes a statistical look at his superb 2021., url: https://www.bbc.co.uk/sport/football/59646200, urlToImage: https://ichef.bbci.co.uk/live-experience/cps/624/cpsprodpb/1269A/production/_122081457_mohamedsalah.jpg, publishedAt: 2021-12-16T08:49:23Z, content: Mohamed Salah has scored 36 goals in all competitions for Liverpool in 2021
I/flutter ( 2307): "He is phenomenal. For sure, at the moment, he is the best player in the world."
I/flutter ( 2307): Liverpool manager Jurgen Klopp may well … [+5278 chars]}, {source: {id: reuters, name: Reuters}, author: null, title: Man Utd face Villa, Leicester host Watford in FA Cup third round - Reuters, description: Manchester United entertain Aston Villa in the FA Cup third round, while holders Leicester City welcome Watford and West Ham United are at home
打印(文章) 由于 articles 为空,请捕获 returns this
I/flutter ( 2307): Caught error: type 'Null' is not a subtype of type 'String' in type cast
article_model
class Article {
Source? source;
String? author;
String? title;
String? description;
String? url;
String? urlToImage;
String? publishedAt;
String? content;
Article(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'] as String,
title: json['title'] as String,
description: json['description'] as String,
url: json['url'] as String,
urlToImage: json['urlToImage'] as String,
publishedAt: json['publishedAt'] as String,
content: json['content'] as String,
);
}
}
source_model
String? id;
String? name;
Source({this.id, this.name});
factory Source.fromJson(Map<String, dynamic> json) {
return Source(id: json['id'], name: json['name']);
}
}
在您的模型上,所有变量都是 String?
类型,也就是说,变量将是 String
或 null
。但是当你制作模型时,你像这样分配所有变量:variable: json['variable'] as String
,这意味着如果它们是 null
他们会抛出错误,因为你做的是 as String
,而不是 as String?
,这就是错误的来源。
要解决此问题,我相信应该可以完全删除 as String
,如下所示:
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'],
title: json['title'],
description: json['description'],
url: json['url'],
urlToImage: json['urlToImage'],
publishedAt: json['publishedAt'],
content: json['content'],
);
}
上面的方法可能不起作用,如果不起作用,则应该:
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
source: Source.fromJson(json['source']),
author: json['author'] as String?,
title: json['title'] as String?,
description: json['description'] as String?,
url: json['url'] as String?,
urlToImage: json['urlToImage'] as String?,
publishedAt: json['publishedAt'] as String?,
content: json['content'] as String?,
);
}