Home > Software engineering >  Union of types in flutter
Union of types in flutter

Time:07-23

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;
  Type1();
}

class Type2 {
  String attr1;
  String attr2;
  Type2();
}

Union2<Type1, Type2> myInstance;

Or

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).

CodePudding user response:

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

This is how we write union with freezed.

@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) {
  print(union.value);
}

Or with pattern matching,

var union = Union(42);

print(
  union.when(
    (int value) => 'Data $value',
    loading: () => 'loading',
    error: (String? message) => 'Error: $message',
  ),
);

CodePudding user response:

Tuple is what you need: https://pub.dev/packages/tuple

Used like this:

const t = Tuple2<String, int>('a', 10);
print(t.item1); // prints 'a'
print(t.item2); // prints 10
  • Related