flutter type_error ai_generated true

type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast

ID: flutter/invalid-runtime-type-cast

Also available as: JSON · Markdown · 中文
95%Fix Rate
90%Confidence
1Evidence
2023-02-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.17.0 active
3.0.0 active
3.13.0 active
3.22.0 active

Root Cause

Casting a decoded JSON list directly to `List<String>` without explicit type checking; JSON decode returns `List<dynamic>`.

generic

中文

在未进行显式类型检查的情况下,直接将解码后的 JSON 列表转换为 `List<String>`;JSON 解码返回 `List<dynamic>`。

Official Documentation

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

Workarounds

  1. 95% success Use `List<String>.from()` or `jsonDecode(data).cast<String>().toList()` to safely convert with type checking.
    Use `List<String>.from()` or `jsonDecode(data).cast<String>().toList()` to safely convert with type checking.
  2. 90% success Decode with explicit type using `jsonDecode` and then iterate to filter or convert each element.
    Decode with explicit type using `jsonDecode` and then iterate to filter or convert each element.
  3. 85% success Use a JSON serialization library like `json_serializable` with proper model classes to avoid raw casts.
    Use a JSON serialization library like `json_serializable` with proper model classes to avoid raw casts.

中文步骤

  1. Use `List<String>.from()` or `jsonDecode(data).cast<String>().toList()` to safely convert with type checking.
  2. Decode with explicit type using `jsonDecode` and then iterate to filter or convert each element.
  3. Use a JSON serialization library like `json_serializable` with proper model classes to avoid raw casts.

Dead Ends

Common approaches that don't work:

  1. 30% fail

    If any element is not a String, `cast()` throws a runtime error; does not handle mixed types.

  2. 50% fail

    Type cast fails at runtime; app crashes when the list is accessed.

  3. 20% fail

    Swallows the error but the list remains untyped; subsequent operations may fail silently.