Skip to content

Instantly share code, notes, and snippets.

@andreciornavei
Created October 25, 2020 16:35
Show Gist options
  • Save andreciornavei/e2715507b6da19d2607b234d32359706 to your computer and use it in GitHub Desktop.
Save andreciornavei/e2715507b6da19d2607b234d32359706 to your computer and use it in GitHub Desktop.
Flutter / Equatable / Entity + Model Sample
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
class UserEntity extends Equatable {
final String id;
final String username;
final String password;
final List<LinkEntity> links;
UserEntity({
@required this.id,
@required this.username,
@required this.password,
@required this.links,
});
@override
List<Object> get props => [id, username, password, links];
}
import 'package:equatable_entity.dart';
import 'package:meta/meta.dart';
import 'link_model.dart';
class UserModel extends UserEntity {
ArtistModel({
String id,
@required String username,
@required String password,
@required List<LinkModel> links,
}) : super(
id: id,
username: username,
password: password,
links: links,
);
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json["id"],
username: json["username"] ?? "",
password: json["password"] ?? "",
links: json["links"] == null ? [] : (json["links"] as List).map((e) => LinkModel.fromJson(e)).toList(),
);
}
factory UserModel.fromEntity(UserEntity entity) {
return UserModel(
id: entity.id,
username: entity.username,
password: entity.password,
links: entity.links,
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"username": username,
"password": password,
"links": links == null ? [] : links.map((e) => LinkModel.fromEntity(e).toJson()).toList(),
};
}
UserEntity toEntity() {
return UserEntity(
id: id,
username: username,
password: password,
links: links,
);
}
}
@wankir
Copy link

wankir commented Jan 19, 2024

Very ceratin.

@neoacevedo
Copy link

But toJson doesn't print a right json object, I mean, the username value is not printed with double quotes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment