Dart Deserialization

Viewed 31

I'm trying to write some deserialization code in Dart. The type system is giving me grief. My understanding is that this is a common conflict. I'm having trouble really believing that there's no workaround. I think one way of boiling down the problem is that if the following worked:

List createListOf(Type t) {
  return <t>[];
}

or you could cast a List<Object> to an e.g. List<String> (as you can in Java, if you cast through Object first), then you could get deserialization to work (for at least any combination of preregistered types, assuming other generic objects behave analogously to List). Specifically, the ability to construct something that can be cast to a generic of type Foo<T>, where T isn't known at compile time. (Some of my objects, for instance, contain a Map<String, Object>, so anything complex that was serialized from that map will have trouble in deserialization.)

There's the mirror package, I hear, but I hear it messes up your code optimization, significantly increases the size of your app, is deprecated/discouraged, and doesn't work in Flutter at all.

Is there really no other workaround? No really ugly string of casts, no obscure operators, no horrifying black magic dealing with pointers and dead cats? (Like, that still at least works in most conditions.) It just doesn't seem like it should be that big an ask.

1 Answers

You can cast a List by casting the objects in it one by one:

objectList.map((object) => object as String).toList();
Related