Search code examples
flutterdartgenericsfreezed

Any thoughts on why I cannot get this freezed (flutter/dart) example (with generics) to build?


I am new to flutter and dart. I'm trying to get the following example to work in my test project:

https://pub.dev/packages/freezed#deserializing-generic-classes

Here is my entire dart file (api_response.dart):

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';

part 'api_response.freezed.dart';
part 'api_response.g.dart';

@Freezed(genericArgumentFactories: true)
class ApiResponse<T> with _$ApiResponse {
  const factory ApiResponse<T>.data(T data) = ApiResponseData;
  const factory ApiResponse<T>.error(String message) = ApiResponseError;

  factory ApiResponse<T>.fromJson(Map<String, dynamic> json, T Function(Object?) fromJsonT) => _$ApiResponseFromJson(json, fromJsonT);
}

When I build with this command:

flutter pub run build_runner build --delete-conflicting-outputs

I receive the following error:

[INFO] Running build...
[SEVERE] freezed:freezed on lib/models/api_response.dart:

This builder requires Dart inputs without syntax errors.
However, package:psf_provider/models/api_response.dart (or an existing part) contains the following errors.
api_response.dart:9:32: Functions must have an explicit list of parameters.
api_response.dart:9:3: Only redirecting factory constructors can be declared to be 'const'.
api_response.dart:9:32: A function body must be provided.
And 13 more...

Here is my pubspec.yaml file definitions to show the versions I'm using:

environment:
  sdk: ">=2.17.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  flutter_hooks: ^0.18.0
  hooks_riverpod: ^2.0.0-dev.9
  dio: ^4.0.0
  flutter_secure_storage: ^4.1.0
  easy_localization: ^3.0.1
  settings_ui: ^2.0.0
  freezed_annotation: ^2.1.0
  json_annotation: ^4.6.0

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0
  build_runner: ^2.2.0
  freezed: ^2.1.0+1
  json_serializable: ^6.3.1

Any ideas? Thanks for looking!


Solution

  • It looks like the docs are outdated. It should be like the following:

    @Freezed(genericArgumentFactories: true)
    class ApiResponse<T> with _$ApiResponse<T> {
      factory ApiResponse.data(T data) = ApiResponseData;
      factory ApiResponse.error(String message) = ApiResponseError;
    
      factory ApiResponse.fromJson(
        Map<String, dynamic> json,
        T Function(Object? json) fromJsonT,
      ) =>
          _$ApiResponseFromJson<T>(json, fromJsonT);
    }