如何修复在 Flutter 和 Swift 之间使用有关数组和字典的消息通道时的转换错误

How to fix a casting error when using the message channel between Flutter and Swift concerning Arrays and Dictionaries

提问人:user1087973 提问时间:10/4/2022 更新时间:10/4/2022 访问量:309

问:

在自定义插件中,我有一些 Swift 代码,我想返回一个字典数组,如下所示:

func myCustomFunc(call: FlutterMethodCall, result: @escaping FlutterResult) {
  var someArrayOfDicts: [[String: Int]] = []
  someArrayOfDicts.append(["fieldA": 12345, "fieldB": 67890])
  result(someArrayOfDicts)
}

但是当我收到错误时:.invokeMethod<List<Map<String, int>>>('myCustomFunc')_CastError (type 'List<Object>' is not a subtype of type 'List<Map<String, int>>' in type cast)

关于消息编解码器的 Flutter 频道文档似乎表明,在 Swift 中,在 Dart 中被接收。ArrayDictionaryListMap

Swift Flutter Casting 消息 传递通道

评论


答:

0赞 Georgina 10/4/2022 #1

根据您的报告:

但是当我收到错误时:.invokeMethod<List<Map<String, int>>>('myCustomFunc')_CastError (type 'List<Object>' is not a subtype of type 'List<Map<String, int>>' in type cast)

我建议这个:

.invokeMethod<List>('myCustomFunc')

因为您已经知道定义了哪些数据类型。您可以尝试从结果列表中提取数据,然后将其设置为所需的格式。

例如:

List<Map<String,int>> x =[];
_listFromInvoke.forEach((element){
 print(element); //print for eg. element.key or element['fieldA'] (Basically trial n error)
});
0赞 user1087973 10/4/2022 #2

有关于这个特定问题的 Flutter 文档invokeMethod

static Future<List<Song>> songs() async {
  // invokeMethod here returns a Future<dynamic> that completes to a
  // List<dynamic> with Map<dynamic, dynamic> entries. Post-processing
  // code thus cannot assume e.g. List<Map<String, String>> even though
  // the actual values involved would support such a typed container.
  // The correct type cannot be inferred with any value of `T`.
  final List<dynamic>? songs = await _channel.invokeMethod<List<dynamic>>('getSongs');
  return songs?.cast<Map<String, Object?>>().map<Song>(Song.fromJson).toList() ?? <Song>[];
}