flutter type_error ai_generated true

type 'String' is not a subtype of type 'int' in type cast

ID: flutter/type-error-json-parse-int

Also available as: JSON · Markdown · 中文
93%Fix Rate
90%Confidence
1Evidence
2023-08-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
flutter 3.13 active
flutter 3.22 active
dart 3.2 active
dart 3.5 active

Root Cause

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.

generic

中文

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

Official Documentation

https://dart.dev/language/type-system

Workarounds

  1. 95% success Parse the string to int explicitly using int.parse() and handle FormatException for invalid input.
    Parse the string to int explicitly using int.parse() and handle FormatException for invalid input.
  2. 90% success Use a safe JSON deserialization approach with a fromJson factory that checks the runtime type and converts accordingly.
    Use a safe JSON deserialization approach with a fromJson factory that checks the runtime type and converts accordingly.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. Using toString() on the value before casting: (json['id'].toString() as int) 90% fail

    toString() returns a String, which cannot be cast to int; the error persists.

  2. Wrapping in a try-catch without parsing and returning a default value 70% fail

    The cast still fails; the catch block may mask the root cause and lead to silent data corruption.