Union of types in flutter

I'm trying to define a union of types in flutter as type of a variable. I would like to achieve something like this:

class Type1 {
  String attr1;
  Map<String, String> attr2;

class Type2 {
  String attr1;
  String attr2;

Union2<Type1, Type2> myInstance;


Union2<String, int> stringOrInt;

I don't want to use dynamic.

I found an old package called union, however it is discontinued. Do you know another way to proceed for my purpose ?

Thanks a lot for your answer !

PS: for information, I need the Union type to create my Hive dataset adapters (boxes may have different object values).


  • You can use freezed which is code generator for data-classes/unions/pattern-matching/cloning.

    This is how we write union with freezed.

    class Union with _$Union {
      const factory Union.data(int value) = Data;
      const factory Union.loading() = Loading;
      const factory Union.error([String? message]) = Error;

    Start using freezed and you won't regret it. It is awesome package to have.

    And the types are, Data, Loading and Error.

    var union = Union(42);
    if(union is Data) {

    Or with pattern matching,

    var union = Union(42);
        (int value) => 'Data $value',
        loading: () => 'loading',
        error: (String? message) => 'Error: $message',