从API获取数据时,我遇到了一个错误,如果颤抖,我应该如何获取数据?
我使用模型从api
获取数据。但是,我遇到了一个问题,即当我获得'Gallery'
数据时,我会遇到一个错误,也就是说,我得到了错误的数据。我需要获取'gallery'
字段,并在其内部使用'url'
字段 - 照片的链接,以便将来使用它。您能告诉我如何正确获取'url'
字段?
{
"data": {
"id": 35,
"picture_url": null,
"email_confirmed": false,
"gallery": [
{
"url": "https://picture-staging.s3.eu-central.jpeg",
"mime_type": "image/jpeg",
"type": "gallery",
"updated_at": "2022",
"created_at": "2022"
}
],
"updated_at": "2022",
"created_at": "2022"
}
}
模型
class User {
final int id;
List? gallery;
User({
required this.id,
this.gallery,
});
User.fromJson(Map<String, dynamic> json)
: this(
id: json['id'] as int,
gallery: json['gallery']['url'],
);
I am getting data from an API
using a model. But I ran into a problem that when I get the 'gallery'
data, I get an error, that is, I get the data incorrectly. I need to get the 'gallery'
field and inside it take the 'url'
field - a link to the photo, in order to use it in the future. Can you tell me how to get the 'url'
field correctly?
{
"data": {
"id": 35,
"picture_url": null,
"email_confirmed": false,
"gallery": [
{
"url": "https://picture-staging.s3.eu-central.jpeg",
"mime_type": "image/jpeg",
"type": "gallery",
"updated_at": "2022",
"created_at": "2022"
}
],
"updated_at": "2022",
"created_at": "2022"
}
}
model
class User {
final int id;
List? gallery;
User({
required this.id,
this.gallery,
});
User.fromJson(Map<String, dynamic> json)
: this(
id: json['id'] as int,
gallery: json['gallery']['url'],
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的API响应中,有一个画廊对象列表,因此您必须穿越所有内容。
有多种工具可以帮助您创建该.fromjson方法,例如 this 。在那里粘贴您的JSON,它将为您生成Dart代码,真的对我有帮助。
用法应该这样:
In your API response, there is a list of gallery objects therefore you have to traverse through all of them.
There are multiple tools that helps you create that .fromJson method, like this. Paste your json there and it will generate dart code for you, really helps me.
The usage should like this:
我希望这不是您的整个模型,因为该模型无法访问
“数据”
json响应中的密钥,您的模型应开始获取键data
然后传递对于在这种情况下应命名用户
的另一个类,这是一个简短的示例
data
类可能是这样的:我建议您使用 quickType
I hope that is not your whole model, because that model is not accessing the
"data"
key on the json response, your model should start getting the keydata
then pass it to another class that in this case should be namedUser
here is a brief example
The
Data
class could be like this:I reccomend you using Quicktype
嘿,您可以使用此工具从JSON生成DART模型。
以下是从上方生成的代码
//您可以这样使用
Hey you can use this tool to generate your dart model from json.
Below is generated code from above tool
// You can use like this