flutter
type_error
ai_generated
true
类型 'String' 不是类型 'int' 的子类型,在类型转换中
type 'String' is not a subtype of type 'int' in type cast
ID: flutter/type-error-json-parse-int
93%修复率
90%置信度
1证据数
2023-08-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| flutter 3.13 | active | — | — | — |
| flutter 3.22 | active | — | — | — |
| dart 3.2 | active | — | — | — |
| dart 3.5 | active | — | — | — |
根因分析
JSON 值是一个字符串(例如 '123'),但直接使用 'as int' 将其转换为 int,而不是使用 int.parse() 或适当的反序列化方法。
English
A JSON value that is a string (e.g., '123') is being cast directly to int using 'as int' instead of parsing it with int.parse() or using a proper deserialization method.
官方文档
https://dart.dev/language/type-system解决方案
-
使用 int.parse() 显式将字符串解析为 int,并处理 FormatException 以应对无效输入。
-
使用安全的 JSON 反序列化方法,使用 fromJson 工厂检查运行时类型并进行相应转换。
无效尝试
常见但无效的做法:
-
Using toString() on the value before casting: (json['id'].toString() as int)
90% 失败
toString() returns a String, which cannot be cast to int; the error persists.
-
Wrapping in a try-catch without parsing and returning a default value
70% 失败
The cast still fails; the catch block may mask the root cause and lead to silent data corruption.