built_value is a beloved package and one of the most popular source generators among Flutter developers. However, working with it isn’t always straightforward, and not every error message is easy to decipher.
Unknown type on deserialization. Need either specifiedType or discriminator field. is another one of those vague error messages that once left the author scratching their head for an entire day trying to fix it!
In reality, this error stems from an issue with the Serializer. The Serializer is something we need to define to tell built_value how we want to serialize and deserialize our data. This problem typically falls into one of three scenarios:
- Forgetting to create the Serializer in the main class file that’s connected to the file you want to generate. You need to include the following code in that class:
static Serializer<MyClass> get serializer => _$myClassSerializer;
- The Serializer used for the
toJsonorfromJsonmethods hasn’t been set up yet. This might happen because you forgot to import the file. Here’s the relevant code:
String toJson() {
return json.encode(ourSerializers.serializeWith(MyClass.serializer, this));
}
static MyClass fromJson(String jsonString) {
return ourSerializers.deserializeWith(
MyClass.serializer, json.decode(jsonString));
}
It’s that ourSerializers reference that can trigger this issue.
- Forgetting to register your class in the Serializer. This code belongs in the custom Serializer you create:
@SerializersFor([
MyClass,
])
📚 Hope you enjoy reading!