Flutter:如何处理 Flutter 和 API + MongoDB 命名约定不同以及名称不匹配的情况?

chi*_*chi 10 flutter

我一直在处理涉及 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);
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ker 18

你有两个选择

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

例如

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

补充阅读:


mir*_*cal 9

除了Rohan的回答之外,如果你想为整个项目设置它,你可以在build.yaml.

targets:
  $default:
    sources:
      exclude:
        - 'example/**'
    builders:
      json_serializable:
        options:
          explicit_to_json: true 
          // this one below
          field_rename: snake
Run Code Online (Sandbox Code Playgroud)

json_serialized 文档。