i wrote this code :
void main() {
int kian = 40;
if (kian > 10) {
print('mamad');
}
}
and now for run I have this error : The operator '>' isn't defined for the type 'String'. Try defining the operator '>'.
how can i fix it? i will be so happy if you answer me :)
CodePudding user response:
You were trying to compare two variables which were of type String.
void main() {
String kian = '40';
if (kian > '10') {
print('mamad');
}
}
//Error message: line 3 • The operator '>'
// isn't defined for the type 'String'.
//Try defining the operator '>'.
However, in your question you provided a running code. Check it here.
CodePudding user response:
With the code, it working fine cause it type is int
. The error may throw from another place.
In case your variable is String
of number like this String kian = '40';
you can write your custom operator in a extension to able to compare them but not recommend. Except you are 100% sure it is an number.
void main() {
try{
print("'40' > '10': ${'40' > '10'}");
print("'40' < '10': ${'40' < '10'}");
print("'40' >= '10': ${'40' >= '10'}");
print("'40' <= '10': ${'40' <= '10'}");
}catch(e){
print('error. the string is not a number');
}
}
extension on String {
operator >(String other){
return double.parse(this) > double.parse(other);
}
operator >=(String other){
return double.parse(this) >= double.parse(other);
}
operator <(String other){
return double.parse(this) < double.parse(other);
}
operator <=(String other){
return double.parse(this) <= double.parse(other);
}
}
Result
'40' > '10': true
'40' < '10': false
'40' >= '10': true
'40' <= '10': false