Dart 2.X List.cast() does not compose

前端 未结 1 838
北恋
北恋 2020-12-19 11:30

The upcoming Dart 2.X release requires strong typing. When working with JSON data we must now cast dynamic types to an appropriate Dart type (not a problem). A

1条回答
  •  囚心锁ツ
    2020-12-19 12:17

    I wrote Ignoring cast fail from JSArray to List, so let me try and help here too!

    So I add the .cast() as the documentation and related link suggest and still receive the warning:

    List docFixBroken = json["data"].cast().map( (s) => s.toUpperCase() ).toList();
    List alsoBroken = List.from( (json["data"] as List).cast() ).map( (s) => s.toUpperCase() ).toList();
    

    Unfortunately, List.from does not persist type information, due to the lack of generic types for factory constructors (https://github.com/dart-lang/sdk/issues/26391). Until then, you should/could use .toList() instead:

    (json['data'] as List).toList()
    

    So, rewriting your examples:

    List docFixBroken = json["data"].cast().map( (s) => s.toUpperCase() ).toList();
    List alsoBroken = List.from( (json["data"] as List).cast() ).map( (s) => s.toUpperCase() ).toList();
    

    Can be written as:

    List notBroken = (json['data'] as List).cast((s) => s.toUpperCase()).toList();
    

    Hope that helps!

    0 讨论(0)
提交回复
热议问题