首页 > 解决方案 > Flutter:如何处理 Flutter 与 API + MongoDB 的命名约定不同以及名称不匹配的问题?

问题描述

我一直在处理涉及 Flutter 和 MongoDB + API 的个人项目。看起来当单词中有空格时,API 倾向于使用_. 喜欢picture_url。当我试图Model在 Flutter 中创建一个。我得到这个Name non-constant identifiers using lowerCamelCase.dart(non_constant_identifier_names)消息。而且,许多使用String prictureUrl格式。

在 Flutter 网站上,它有json_serialization示例https://flutter.dev/docs/development/data-and-backend/json。而且,它有没有空格的单词。但是,如果我的 apis 发送picture_url和 Flutter 上的模型设置为pictureUrl,我如何使用模型进行转换?

或者,该领域的人如何处理这个问题?他们在后端和前端设置名称的方式是否相同?

- - 编辑

@JsonSerializable()
class User {
  User(this.profileUrl, this.email);

  String profileUrl;
  String email;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

标签: flutter

解决方案


你有两个选择

  1. @JsonSerializable.fieldRename
  2. 向字段添加@JsonKey注释并在那里设置属性。

例如

@JsonSerializable(fieldRename:FieldRename.snake)
class User {
...
}
class User {
    ...
    @JsonKey(name:'picture_url')
    String pictureUrl;
    ...
}

补充阅读:


推荐阅读