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

前端 未结 1 853
北恋
北恋 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<String>, so let me try and help here too!

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

    List<String> docFixBroken = json["data"].cast<String>().map( (s) => s.toUpperCase() ).toList();
    List<String> alsoBroken = List.from( (json["data"] as List).cast<String>() ).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<String> docFixBroken = json["data"].cast<String>().map( (s) => s.toUpperCase() ).toList();
    List<String> alsoBroken = List.from( (json["data"] as List).cast<String>() ).map( (s) => s.toUpperCase() ).toList();
    

    Can be written as:

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

    Hope that helps!

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