Trying to assign an instance of class NumberTrivia
to an instance of class NumberTriviaModel
but it is giving me the error:
The argument type 'NumberTrivia' can't be assigned to the parameter type 'NumberTriviaModel'.
. So I tried to cast it but now I get an uncaught error. Reso code could assign NumberTrivia to NumberTriviaModel before. But it was an older dart version and it can't be done the same way now. Now the main question is how to do so in the newer dart version.
void main() {
NumberTrivia remoteTrivia = NumberTrivia(text : "Text", number : 5);
cacheNumberTrivia(remoteTrivia as NumberTriviaModel);
}
class NumberTrivia {
final String text;
final int number;
NumberTrivia({
required this.text,
required this.number,
});
}
class NumberTriviaModel extends NumberTrivia {
NumberTriviaModel({
required String text,
required int number,
}) : super(text: text, number: number);
factory NumberTriviaModel.fromJson(Map<String, dynamic> json) {
return NumberTriviaModel(
text: json['text'],
number: (json['number'] as num).toInt(),
);
}
Map<String, dynamic> toJson() {
return {
'text': text,
'number': number,
};
}
}
void cacheNumberTrivia(NumberTriviaModel triviaToCache) {
print(triviaToCache.number);
}
but it's giving me the following error
Uncaught Error: TypeError: Instance of 'NumberTrivia': type 'NumberTrivia' is not a subtype of type 'NumberTriviaModel'
CodePudding user response:
Instance of 'NumberTrivia':
type 'NumberTrivia' is not a subtype of type 'NumberTriviaModel'
This means that NumberTrivia
does not extend NumberTriviaModel
.
Looking at the code, it is the other way around. NumberTriviaModel
extends NumberTrivia
, NumberTriviaModel
is a sub-type NumberTrivia
:
class NumberTriviaModel extends NumberTrivia {
! SUBTYPE ! TYPE
Your headline states Type "A" is not a sup type of type "B" even though A extends B
. But the code does not reflect that.
Instead, the code can be described as Type "A" is not a sup type of type "B" BECAUSE B extends A
.
CodePudding user response:
The way you are calling the method is wrong. Here A extends B. If you want to access method of A you need to use instance of A. If you have added method in B and tried to access via instance of A, you can use it.
void main() {
NumberTriviaModel remoteTrivia = NumberTriviaModel(text : "Text", number : 5);
cacheNumberTrivia(remoteTrivia as NumberTriviaModel);
}
class NumberTrivia {
final String text;
final int number;
NumberTrivia({
required this.text,
required this.number,
});
}
class NumberTriviaModel extends NumberTrivia {
NumberTriviaModel({
required String text,
required int number,
}) : super(text: text, number: number);
factory NumberTriviaModel.fromJson(Map<String, dynamic> json) {
return NumberTriviaModel(
text: json['text'],
number: (json['number'] as num).toInt(),
);
}
Map<String, dynamic> toJson() {
return {
'text': text,
'number': number,
};
}
}
void cacheNumberTrivia(NumberTriviaModel triviaToCache) {
print(triviaToCache.number);
}