# 类型 'Null' 不是类型 'int' 的子类型，类型转换失败

- **ID:** `flutter/typeerror-null-not-subtype-int`
- **领域:** flutter
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

在期望非空 int 的地方分配或返回了 null 值，通常是由于 JSON 解析或 API 响应中缺少空安全处理。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.0 | active | — | — |
| Flutter 3.3 | active | — | — |
| Flutter 3.7 | active | — | — |

## 解决方案

1. ```
   Use null-safe access with a fallback value:
int value = (json['field'] as int?) ?? 0;
   ```
2. ```
   Use a JSON parsing library like 'json_serializable' with nullable fields defined properly:
@JsonKey(name: 'field', defaultValue: 0)
int field;
   ```
3. ```
   Add explicit null checks before casting:
if (json['field'] != null) {
  int value = json['field'] as int;
} else {
  // handle null case
}
   ```

## 无效尝试

- **Using 'as int' without null check** — If the value is null, the cast will throw the same error. (90% 失败率)
- **Ignoring null-safety and using 'dynamic' instead of 'int'** — Defeats the purpose of null safety and can lead to runtime type errors elsewhere. (70% 失败率)
- **Assuming the API will never return null for that field** — APIs can change or return null for missing fields; brittle assumption. (80% 失败率)
