Home > Net >  Union class with template type
Union class with template type

Time:06-15

I'm trying to build a union type for api responses.

I found freezed package supports union types and I tried out without issues. But as the api return different classes (responses) I think using a template type is suitable to keep the class as generic as possible.

This is the file I created:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'api_response.freezed.dart';

@freezed
class ApiResponse<T> with _$ApiResponse {
  const factory ApiResponse.success(T content, String? message) = _Data;
  const factory ApiResponse.failed(String? message, Object? exception) = _Error;
}

But when the build_runner generates the part file, there is an error on it:

error on generated file

Is there a way to fix it? Or another way to implement it?

Thanks in advance

CodePudding user response:

It should work as follows:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'test_union.freezed.dart';

@freezed
class TestUnion<T> with _$TestUnion<T> {
  const factory TestUnion.foo(T fubar) = _Foo<T>;
}

You can then use it as:

const foo = TestUnion<String>.foo("fubar");

So give this a go:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'api_response.freezed.dart';

@freezed
class ApiResponse<T> with _$ApiResponse<T> {
  const factory ApiResponse.success(T content, String? message) = _Data<T>;
  const factory ApiResponse.failed(String? message, Object? exception) = _Error;
}
  • Related