简体   繁体   中英

type 'List<Object?>' is not a subtype of type 'List<>' in type cast

What I'm trying to do is to communicate between Flutter and Android. For this I'm using EventChannel and MethodChannel. Due to codec restrictions I need to wrap my Android data in HashMap before sending it to Flutter. On the Flutter side I'm trying to unwrap it for display in the simple ListView. However, I have problem with typecasting that I can't figure out

factory BLEService.fromMap(Map<String, dynamic> map) => BLEService(
    map['uuid'] as String,
    (map['characteristics'] as List<BLECharacteristic>)
        .map<BLECharacteristic>((e)  =>
      BLECharacteristic.fromMap(e as Map<String, BLECharacteristic>)
    ).toList()
  );

For this line the following exception is thrown:
type 'List<Object?>' is not a subtype of type 'List<BLECharacteristic>' in type cast

Help to solve this issue would be greatly appreciated


Edit
Flutter BLECharacteristic.fromMap

factory BLECharacteristic.fromMap(Map<String, dynamic> map) => BLECharacteristic(
    map['uuid'] as String,
  );

Java BLECharacteristic.toMap

HashMap<String, Object> toMap() {
        HashMap<String, Object> bleCharacteristicMap = new HashMap<>();
        bleCharacteristicMap.put("uuid", uuid);
        return bleCharacteristicMap;
    }

In Flutter the map['characteristics'] will return a List<Object?> and not a List<BLECharacteristic> . So the below code might work for you (not tested):

factory BLEService.fromMap(Map<String, dynamic> map) => BLEService(
    map['uuid'] as String,
    (map['characteristics'] as List)
        ?.map((e)  =>
      BLECharacteristic.fromMap(e as Map<String, dynamic>)
    ).toList()
  );

Can you show the fromMap and toMap methods for BLECharactertic for better understanding of the problem.

try this code once

List<BLECharacteristic> bleCharacteristicFromJson(List list) =>
List<BLECharacteristic>.from(
      list.map((x) => BLECharacteristic.fromJson(x)));

class BLECharacteristic {
  BLECharacteristic({this.uuid});

  String? uuid;

  factory BLECharacteristic.fromJson(Map<String, dynamic> json) =>
      BLECharacteristic(
        uuid: json["uuid"],
      );
}

and call it like this

final data = bleCharacteristicFromJson(map["characteristics"]); // will return you list of BLECharacteristic

In the end I figured out a bit hacky method to solve it:

var finalList = Map<String, dynamic>.from(jsonDecode(jsonEncode(data)))['SERVICESLIST'].map<BLEService>((e) => BLEService.fromMap(e)).toList();

However, to make simple I just changed the Android implementation to wrap the data using JSON with gson plugin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM