如何在 Dart 中比较运算符"is"类型变量



我找不到在Map中存储Type值的方法,这样我就可以在is运算符中使用它来检查稍后使用此映射的类型的有效性。此外,is运算符可以接受Type作为变量吗?

例如,下面是解决问题的假设代码,但它是无效的。

Map<String, Type> map = {
"sku": String,
"price": double,
"quantity": int,
};
dynamic value = 10;
if(value is map["quantity"]){
print("value is of type int and int is expected for quantity value");
}

您可以这样做:

class TypeCheck<T> {
const TypeCheck();
bool typeCheck(dynamic value) => value is T;
}
void main() {
Map<String, TypeCheck> map = {
"sku": TypeCheck<String>(),
"price": TypeCheck<double>(),
"quantity": TypeCheck<int>(),
};
dynamic value = 10;
if (map["quantity"]!.typeCheck(value)) {
print("value is of type int and int is expected for quantity value");
}
}

我不确定我是否完全理解我理解你想做什么,但你为什么不尝试一下呢。

bool _validate(Map productDetails){
if (productDetails.containsKey("sold_individually") && productDetails["sold_individually"] is bool) {
//return true or false 
}
else if (productDetails.containsKey("stock_quantity") && productDetails["stock_quantity"] is int){
//return true or false 
}
else if (productDetails.containsKey("tax_class") && productDetails["tax_class"] is String && productDetails["tax_class"].isNotEmpty) {
//return true or false 
} else {
//return true or false 
}
}

至于你问题的另一部分,你不会得到错误,但你总是会返回错误。相反,如果您检查一个变量是否是动态的,它将始终返回true。

我真的不明白你的最终目标。但从你所拥有的来看,我不认为你在利用飞镖的强类型性。

  • 假设您从API获取地图,您可以强制手动键入您的代码,如下所示
Map<String, Type> map = {
"sku": json['key'] as String,
"price": json['key'] as double,
"quantity": json['key'] as int,
};

在声明变量时避免使用dynamic

  • 如果你有一个用户定义的类型,你可以比较什么,你可以在一个类上使用等价包,例如如下所示
class CustomMap extends Equatable {
String sky;
double price;
int quantity;
// here you put the fields of a class you want for two instances of a class to be equal. 
@overide 
List<Object> get props => [sky, price, quantity]; 
}

根据您的评论更新

例如,您应该有一个用于API对象的自定义类;

class Item extends Equatable {
String sku;
double price;
int quantity;

Item({this.sky, this.price, this.quantity});
// factory constructor 
factory Item.fromMap(Map<String, dynmic> json) {
final sku = json['sku'] as String,
final price = (json['price'] as num) as double,
final quantity = json['quantity'] as num,
return Item(sku: sku, price: price, quantity: quantity);
}
// define equatable objects
@override
List<Object> get props => [sku, price, quantity];
}

现在您可以按如下方式使用它;

Future<Item> objectsFromService(Map<String, dynamic> json ) async {
http.Response response = http.get(url);
if(response.status == 200) {
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}else{
print('Error fetch data');
return null;
}
}

希望它能帮助

最新更新