For example, every time I want to create a new entity or model, there is an attribute called global
that I need to set to true or false depending on its other attribute called id
:
If the id
is 0, I want the global
to be true
Entity :
class Folder extends Equatable {
const Folder({
required this.id,
required this.global /// here i want this.global = (id == 0)
});
final int id;
final bool global;
@override
List<Object> get props {
return [
id,
global,
];
}
}
Model :
class FolderModel extends Folder{
FolderModel ({
required this.id,
required this.global,
}) : super(
id: id,
global: global,
);
FolderModel copyWith({
int? id,
bool? global,
}) {
return FolderModel(
id: id ?? this.id,
global: global ?? this.global,
);
}
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'id': id});
result.addAll({'global': global});
return result;
}
factory FolderModel.fromMap(Map<String, dynamic> map) {
return FolderModel(
id: map['id']?.toInt() ?? 0,
global: map['global'] ?? false,
);
}
String toJson() => json.encode(toMap());
factory FolderModel.fromJson(String source) => FolderModel.fromMap(json.decode(source));
}
Where should I add that, or should I create a special function to read that value ? or just don’t add anything and everything is logic out of these classes ?
3
Answers
I think you can try use factory constructor :
IMO this will work for your issue:
The best way would be to make
global
a getter, since you don’t use it anyway.In case you do want the explicit option of having a global with an id, the simplest way to achieve this is:
By making
global
a non-required named parameter, it is optional. If you set it, the value will be used, if you don’t, the value will be calculated.This will print: