我正在嘗試為 api 回應構建聯合型別。
我發現 freezed 包支持聯合型別,我嘗試過沒有問題。但是由于 api 回傳不同的類(回應),我認為使用模板型別適合使類盡可能通用。
這是我創建的檔案:
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;
}
但是在build_runner生成part檔案的時候,上面就報錯了:

有沒有辦法解決它?還是另一種實作方式?
提前致謝
uj5u.com熱心網友回復:
它應該按如下方式作業:
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>;
}
然后,您可以將其用作:
const foo = TestUnion<String>.foo("fubar");
所以試一試:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491012.html
下一篇:Flutter_CLI:因為flutterfire_cli每個版本都依賴xml>=5.3.0,需要SDK版本>=2.14.0<3.0.0,所以flutterfire_cli是被禁止的
