Flutter: How to deal with the different convention of naming between Flutter and API + MongoDB and mis-match in names?

Issue

I’ve been dealing with my personal project involving Flutter and MongoDB + APIs. Looks like when there is a space in words, APIs tend to use _. Like picture_url. When I am trying to create a Model in Flutter. I get this Name non-constant identifiers using lowerCamelCase.dart(non_constant_identifier_names) message. And, many use String prictureUrl format.

On Flutter website, it has json_serialization example https://flutter.dev/docs/development/data-and-backend/json. And, it has words without space. However, if my apis sending picture_url and the model on Flutter is set to pictureUrl, how can I convert this by using the model?

Or, how do people in the field deals with this? Do they set the names the same ways on backend and frontend?

—- edit

@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);
}

Solution

You have two options

  1. Set @JsonSerializable.fieldRename
  2. Add a @JsonKey annotation to a field and set properties there.

For Example

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

Additional Reading:

Answered By – Rohan Thacker

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *