如何比较Dart中“ is”运算符中的类型变量

时间:2020-04-09 18:13:10

标签: flutter dart

我找不到在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");
}

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解我的理解,但是您为什么不尝试类似的事情。

library(dplyr)
iris %>% 
   mutate_at(vars(Species), ~ setNames(c(0, 1, NA),
          c('setosa', 'versicolor', 'virginica'))[as.character(.)])

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

答案 1 :(得分:0)

我不太了解您的最终目标。但是从您拥有的东西来看,我认为您没有利用飞镖的强类型特性。

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

并且在声明变量时避免使用dynamic

OR

  • 如果您要比较的是用户定义的类型,则可以在类上使用equatable包,例如,如下所示;
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;
    }

}

希望有帮助