I want to implement copyWith()
method for my class. Since its inhirited class, i got error:
The member being overridden.
my basemodel
class BaseData {
int id;
String? createdAt, updatedAt;
BaseData({this.id = 0, this.createdAt, this.updatedAt});
BaseData copyWith(
{int? id, String? createdAt, String? updatedAt}) {
return BaseData(
CreatedAt: createdAt ?? this.createdAt,
ID: id ?? this.id,
UpdatedAt: updatedAt ?? this.updatedAt);
}
}
and I have another class that extend to my BaseData
model
class QcData extends BaseData{
String name;
QcData ({this.name =""});
@override
QcData copyWith({
String? name
}){
return QcData(name: name ?? this.name);
}
}
How to create copyWith()
method for my model class?
Thanks in advance.
CodePudding user response:
inheritance means that a class member's definitions should remain the same when you extend, or implement a base class, in your case by doing the:
@override
QcData copyWith({
String? name
}){
return QcData(name: name ?? this.name);
}
this method declaration is not the same as the BaseData
's since they take different sets of arguments, you should remain the arguments the same as the BaseData
, so your code should be this in order to work:
class QcData extends BaseData {
String name;
QcData({this.name = ""});
@override
QcData copyWith({
int? id,
String? createdAt,
String? updatedAt,
}) {
return QcData(name: name ?? this.name);
}
}
CodePudding user response:
We also need to pass data on while creating QcData(child). I prefer modifying constructor this way.
const QcData({
this.name = "",
super.id,
super.createdAt,
super.updatedAt,
});
Now we have access on copyWith method these property, another cause is I like to use const
constructor with final fields.
@override
QcData copyWith({
String? name,
int? id,
String? createdAt,
String? updatedAt,
}) {
return QcData(
name: name ?? this.name,
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
The models will be
class BaseData {
final int id;
final String? createdAt;
final String? updatedAt;
const BaseData({this.id = 0, this.createdAt, this.updatedAt});
BaseData copyWith({
int? id,
String? createdAt,
String? updatedAt,
}) {
return BaseData(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
}
class QcData extends BaseData {
final String name;
const QcData({
this.name = "",
super.id,
super.createdAt,
super.updatedAt,
});
@override
QcData copyWith({
String? name,
int? id,
String? createdAt,
String? updatedAt,
}) {
return QcData(
name: name ?? this.name,
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
}