Flutter 如何在dart中使用JSONECODE/jsonDecode将模型作为字符串正确传递 问题总结
我正在使用一个Flutter 如何在dart中使用JSONECODE/jsonDecode将模型作为字符串正确传递 问题总结,flutter,dart,Flutter,Dart,我正在使用一个SreamTransformer来验证一个简单的字符串值,为此我正在调用一个Future fetchCountry函数,该函数进行API调用并解析对Country类的响应。我试图将类作为字符串返回,如下所示: static Future fetchCountry(country)async{ ... 打印('fetch ok');//这是打印的 返回jsonEncode(国家/地区)( 大陆:大陆, 国家:countryR,, 人口:人口,, 新案例:新案例, 活动案例:活动案例,
SreamTransformer
来验证一个简单的字符串
值,为此我正在调用一个Future fetchCountry
函数,该函数进行API调用并解析对Country
类的响应。我试图将类作为字符串返回,如下所示:
static Future fetchCountry(country)async{
...
打印('fetch ok');//这是打印的
返回jsonEncode(国家/地区)(
大陆:大陆,
国家:countryR,,
人口:人口,,
新案例:新案例,
活动案例:活动案例,
关键时刻:关键时刻,
已恢复案例:已恢复案例,
totalcases:totalcases,
新死亡:新死亡,
死亡总数:死亡总数,
天:天);;
}
调用被执行并返回200
,尽管此函数始终返回null
我所尝试的:
- 阅读颤振文档,了解更多信息
- 我正在从
fetchCountry
返回Country
,但将其更改为String
,因为流无法读取Country
对象
验证程序中的代码:
Future<String> future = FetchCountry.fetchCountry(country);
future.then((value) {
print('$value'); //this is always null!!
sink.add(value);
}).catchError((err) {
sink.addError("$country is not a country from future");
// this is shown but the future doesn't return Future.error on `fetch ok` message
});
最后但并非最不重要的国家/地区车型类别:
class Country {
String country;
String continent;
int population;
String newcases;
int activecases;
int criticalcases;
int recoveredcases;
int totalcases;
String newdeaths;
int totaldeaths;
String day;
Country(
{this.country,
this.continent,
this.population,
this.newcases,
this.activecases,
this.criticalcases,
this.recoveredcases,
this.totalcases,
this.newdeaths,
this.totaldeaths,
this.day});
}
我完全遗漏了什么,并且无法正确返回json字符串?您引用的flift文档在普通类中为User提供了一个toJson方法-您的国家代码需要相同的方法吗
根据用户示例:
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};
Map to json()=>
{
“名称”:名称,
“电子邮件”:电子邮件,
};
来自文档:要对用户进行编码,请将用户对象传递给jsonecode()函数。你不需要调用toJson()方法,因为jsonecode()已经为你做了。我将尝试添加一个toJson,也许它必须包含在jsonecode中才能工作你不需要调用toJson()方法,因为jsonecode()已经为你做了。
但是你的模型不需要使用json()所以基本上我需要添加一个toJson方法
class Country {
String country;
String continent;
int population;
String newcases;
int activecases;
int criticalcases;
int recoveredcases;
int totalcases;
String newdeaths;
int totaldeaths;
String day;
Country(
{this.country,
this.continent,
this.population,
this.newcases,
this.activecases,
this.criticalcases,
this.recoveredcases,
this.totalcases,
this.newdeaths,
this.totaldeaths,
this.day});
}
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};