# 类型 'String' 不是类型 'int' 的子类型，在类型转换中

- **ID:** `flutter/type-error-json-parse-int`
- **领域:** flutter
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 93%

## 根因

JSON 值是一个字符串（例如 '123'），但直接使用 'as int' 将其转换为 int，而不是使用 int.parse() 或适当的反序列化方法。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| flutter 3.13 | active | — | — |
| flutter 3.22 | active | — | — |
| dart 3.2 | active | — | — |
| dart 3.5 | active | — | — |

## 解决方案

1. ```
   使用 int.parse() 显式将字符串解析为 int，并处理 FormatException 以应对无效输入。
   ```
2. ```
   使用安全的 JSON 反序列化方法，使用 fromJson 工厂检查运行时类型并进行相应转换。
   ```

## 无效尝试

- **Using toString() on the value before casting: (json['id'].toString() as int)** — toString() returns a String, which cannot be cast to int; the error persists. (90% 失败率)
- **Wrapping in a try-catch without parsing and returning a default value** — The cast still fails; the catch block may mask the root cause and lead to silent data corruption. (70% 失败率)
