Home > database >  How to fix a casting error when using the message channel between Flutter and Swift concerning Array
How to fix a casting error when using the message channel between Flutter and Swift concerning Array

Time:10-04

In a custom plugin i have some Swift code that I'd like to return an array of dictionaries like so:

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

but when I .invokeMethod<List<Map<String, int>>>('myCustomFunc') I get an error: _CastError (type 'List<Object>' is not a subtype of type 'List<Map<String, int>>' in type cast)

The Flutter channel docs about the messaging codec seem to indicate that Array and Dictionary in Swift get received as List and Map in Dart.

CodePudding user response:

Based on your report:

but when I .invokeMethod<List<Map<String, int>>>('myCustomFunc') I get an error: _CastError (type 'List<Object>' is not a subtype of type 'List<Map<String, int>>' in type cast)

I suggest this:

.invokeMethod<List>('myCustomFunc')

Because you already know what data types are defined. You can try to extract the data from the resulting list and then set it to to your desired format.

For example:

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

CodePudding user response:

There is Flutter documentation about this specific issue for the 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>[];
}
  • Related