![](/img/trans.png)
[英]Showing Error (The operator '+' isn't defined for the type 'Uri'. Try defining the operator '+'.dart (undefined_operator))
[英]The operator '>' isn't defined for the type 'String'. Try defining the operator '>'. error in dart
我寫了這段代碼:
void main() {
int kian = 40;
if (kian > 10) {
print('mamad');
}
}
現在運行我有這個錯誤:運算符'>'沒有為'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 '>'.
但是,在您的問題中,您提供了一個運行代碼。 在這里檢查。
使用代碼,它工作正常,因為它的類型是int
。 錯誤可能從另一個地方拋出。
如果您的變量是這樣的數字字符串String
String kian = '40';
您可以在擴展中編寫自定義運算符以便能夠比較它們,但不推薦。 除非你 100% 確定它是一個數字。
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);
}
}
結果
'40' > '10': true
'40' < '10': false
'40' >= '10': true
'40' <= '10': false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.