Reputation: 83
how to check the prop type when using it like this below
void main(){
var obj = Ball<PassData>(data: PassData(id: 1,nama: 'asdas'));
print('${obj.get()}');
}
class Ball<T>{
T data;
Ball({this.data});
String get(){
if(data is PassData){ //can't check it this way
return 'this type has ${data.id} and ${data.nama}'; //compile error
}
else{
return 'no : $data';
}
}
}
class PassData{
String nama;
int id;
PassData({this.nama,this.id});
}
when using property of PassData object I've got an compile error like above. I need to get type of 'data' type property. Am I doing it wrong?
Upvotes: 0
Views: 1176
Reputation: 318
Currently your data is in T type and your get class does not know which class it is belong to and therefore can not handle the operations. You can try this:
String get(){
if(this.data is PassData){
return 'this type has ${(data as PassData).id} and ${(data as PassData).nama}';
}
else{
return 'no : $data';
}
}
Upvotes: 0
Reputation: 71613
Your problem is not that the type is generic, but that the variable is not a local variable.
Dart only promotes local variables, so doing if (data is PassData)
doesn't promote the instance variable/field data
to be a PassData
.
Try writing it as:
String get() {
var data = this.data;
if (data is PassData) {
return 'this type has ${data.id} and ${data.nama}';
} else {
return 'no: $data';
}
}
Upvotes: 2