【问题标题】:Why is parse method throwing a type 'int' is not a subtype of type 'String' error?为什么解析方法抛出类型'int'不是类型'String'错误的子类型?
【发布时间】:2020-08-06 18:59:48
【问题描述】:

我有一个非常简单的方法,可以将动态变量转换为 int,如下所示:

  int _convertedNum(dynamic number){
    int intNumber = int.parse(number);

    return intNumber;
  }

我有这个模型类:

class Properties {

    dynamic popEst;


    dynamic confirmed;

    Properties({

        this.popEst,

        this.confirmed
    });

    factory Properties.fromJson(String str) => Properties.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Properties.fromMap(Map<String, dynamic> json) => Properties(

        popEst: json["pop_est"],

        confirmed: json["confirmed"]
    );

    Map<String, dynamic> toMap() => {

        "pop_est": popEst,

        "confirmed": confirmed
    };
}

现在,当我尝试使用该方法将上面类中的属性从动态转换为 int 时:

_convertedNum(properties.popEst);

我得到 type 'int' is not a subtype of type 'String' 错误。我尝试将属性从动态更改为字符串,仍然是同样的错误。

我也尝试对 json 执行此操作:

confirmed: json["confirmed"].toInt();

也抛出类似的错误。

请问如何将属性转换为整数?

【问题讨论】:

  • 房产编号是多少?

标签: json flutter dart


【解决方案1】:

您传递的数据是整数类型。您可以尝试像这样检查数据类型:

if(number is int){ 

}

【讨论】:

    【解决方案2】:

    这是因为parse,正如它的文档所说,采用String 的源并将其转换为int,而您正在做的(从错误中)将裸ints 传递给@ 987654325@,

    解决方案:

    int func(dynmaic number){
        int intNumber = int.parse(number.toString());
    
        return intNumber;
      }
    

    【讨论】:

    • 非常感谢您,您的解释是一流的!完全澄清了我的困惑!
    • 只是一个建议,如果您想保持动态,请指定除动态以外的类型或声明声明以避免在应用程序投入生产之前出现这些错误
    • 好的。我一定会这样做的!再次感谢。
    【解决方案3】:

    也许您的某些属性已经是整数。由于int.parse() 想要一个String 作为参数,也许这样做:

    int _convertedNum(dynamic number){
      int intNumber = int.parse(number.toString());
    
      return intNumber;
    }
    

    可以解决您的问题。

    【讨论】:

    • 是的!...它确实做到了!谢谢
    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2020-04-23
    • 2020-12-14
    • 1970-01-01
    • 2021-06-21
    • 2020-06-01
    相关资源
    最近更新 更多