标签: flutter-freezed

类型转换错误中,类型“Null”不是类型“Map<String,dynamic>”的子类型

在我的示例项目中,我使用riverpod包和freezed. 在下面的代码中,我可以成功从服务器获取数据,但是当我尝试使用时model.fromJson出现此错误:

getting type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
Run Code Online (Sandbox Code Playgroud)

服务器响应数据:

getting type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
Run Code Online (Sandbox Code Playgroud)

login模型来转换服务器响应的数据和结构:

{
  "message": "test message",
  "statusCode": 1
}
Run Code Online (Sandbox Code Playgroud)

在LoginResponse类中,我定义了两个参数message,statusCode它们由服务器返回。当我尝试使用此请求时,例如:

LoginModel loginModelFromJson(Map<String, dynamic> str) => LoginModel.fromJson(str);

String loginModelToJson(LoginModel data) => json.encode(data.toJson());

@freezed
class LoginModel with _$LoginModel {
  const factory LoginModel({
    required LoginResponse response,
  }) = _LoginModel;

  factory …
Run Code Online (Sandbox Code Playgroud)

dart flutter riverpod flutter-freezed

9
推荐指数
1
解决办法
3万
查看次数

具有枚举属性的冻结类在尝试序列化时会引发错误

我有一个冻结的类,它在其构造函数中采用枚举,但是当尝试在此类上执行 jsonEncode 方法时,它失败并出现以下错误:

处理手势时抛出以下 JsonUnsupportedObjectError:将对象转换为可编码对象失败:“InputType”实例

我已用 JsonValue("...") 注释了我的枚举案例,但我没有看到任何为枚举生成的代码。

这是一个错误还是我做错了什么?

完整示例如下:

@freezed
class Input with _$Input {
  const factory Input({
    @Default(0) int seconds,
    @Default(0) double bolus,
    @Default(0) double infusion,
    @Default(InputType.Bolus) currentInputType,
  }) = _Input;

  factory Input.fromJson(Map<String, dynamic> json) => _$InputFromJson(json);
}

enum InputType {
  @JsonValue("bolus")
  Bolus,
  @JsonValue("infusion")
  Infusion,
}

// When calling jsonEncode(someInput); throws the specified error.

Update: freezed needs the enum type specified in the factory constructor! Default value is not enough.
Run Code Online (Sandbox Code Playgroud)

enums flutter json-serializable freezed flutter-freezed

7
推荐指数
1
解决办法
6704
查看次数

json_serialized - 将通用字段添加到 freezed/json_serializing 类

如何使Freezed对象采用泛型类型?我想做这个:

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:vepo/src/entity_types/option_entity.dart';

part 'vegan_item_tag.freezed.dart';
part 'vegan_item_tag.g.dart';

@freezed
abstract class VeganItemTag<T>
    with _$VeganItemTag<T>
    implements OptionEntity<T> {
  const factory VeganItemTag({int? iconCodePoint, T? id, String? name}) =
      _VeganItemTag;

  const VeganItemTag._();

  factory VeganItemTag.fromJson(Map<String, dynamic> json) =>
      _$VeganItemTagFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用@With.fromString('AdministrativeArea<House>')文档中的内容,但无法将其正确应用到此类。

错误之一:

lib/src/common/enums/tags/common/vegan_item_tag.freezed.dart:142:32:错误:位置参数太少:需要 2 个,给定 1 个。
$ $_VeganItemTagFromJson(json);

我想我可能是在正确的轨道上,但它不再生成文件vegan_item_tag.g.dart:

@freezed
abstract class VeganItemTag<T>
    with _$VeganItemTag<T>
    implements OptionEntity<T> {
  const factory VeganItemTag(
      {required int iconCodePoint,
      required T id,
      required String name}) = _VeganItemTag;

  const VeganItemTag._();

  factory VeganItemTag.fromJson( …
Run Code Online (Sandbox Code Playgroud)

dart flutter json-serializable freezed flutter-freezed

5
推荐指数
1
解决办法
7090
查看次数

flutter :需要冻结或用 @Default 标记

我正在尝试在我的应用程序上使用冻结,所以我添加了

\n
environment:\n  sdk: ">=2.7.0<3.0.0"\n\n  freezed: ^0.14.0\n  freezed_annotation: ^0.14.0\n
Run Code Online (Sandbox Code Playgroud)\n

到我的依赖。

\n
dev_dependencies:\n  freezed_annotation: ^0.12.0\n  build_runner:  ^2.0.1\n  retrofit_generator:\n  flutter_localizations:\n    sdk: flutter\n  flutter_test:\n    sdk: flutter\n
Run Code Online (Sandbox Code Playgroud)\n

之后我创建简单的冻结类:

\n
import 'package:freezed_annotation/freezed_annotation.dart';\n\npart 'chart_daily_expanded_detailes_model.freezed.dart';\n\n@freezed\nabstract class ChartDailyExpandedDetailesModel\n    with _$ChartDailyExpandedDetailesModel {\n  const factory ChartDailyExpandedDetailesModel({\n    String title,\n    String testNumber,\n    String testPercentage,\n    String icon,\n  }) = _ChartDailyExpandedDetailesModel;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但我收到了这个错误:

\n
[SEVERE] freezed:freezed on lib/new_develop/model/test/chart_daily_expanded_detailes_model.dart:\n\nThe parameter `title` of `ChartDailyExpandedDetailesModel` is non-nullable but is neither required nor marked with @Default\npackage:app/new_develop/model/test/chart_daily_expanded_detailes_model.dart:9:12\n  \xe2\x95\xb7\n9 \xe2\x94\x82     String title,\n
Run Code Online (Sandbox Code Playgroud)\n

这是颤振医生:

\n
Doctor summary (to …
Run Code Online (Sandbox Code Playgroud)

flutter freezed flutter-freezed

5
推荐指数
1
解决办法
5788
查看次数

Flutter Firebase 如何将 DocumentSnapshot 转换为模型类中的 Model Json

我有一个 Firebase 文档,我想将其转换为 JSON 并在应用程序中使用它时向其中添加 Id。

factory Recipe.fromDocument(DocumentSnapshot doc) {
    final data = doc.data()!;
    return Recipe.fromJson(data).copyWith(id: doc.id);
  }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误 在此输入图像描述

firebase flutter google-cloud-firestore flutter-freezed

5
推荐指数
1
解决办法
2830
查看次数

flutter:由于不支持的操作而无法修改列表:无法修改不可修改的列表

我正在尝试修改列表中的项目值,这总是会导致Can't modify list because of Unsupported operation: Cannot modify an unmodifiable list

我正在使用块状态管理和冻结作为代码生成器。这是我的代码:

从服务器获取角色并将列表添加到角色

Future<RoleWithNeeds> getRoleWithNeeds({
    required RoleWithNeeds selectedRoles,
  }) async {
    final dataFromApi = await _apiClient.fetchNeedsByRoles(selectedRoles.idRole);

    final needsApi = dataFromApi.data;
    final needsRepository = <Need>[];

    // convert to a repository model
    for (var i = 0; i < needsApi.length; i++) {
      needsRepository.add(Need(
        id: needsApi[i].id,
        name: needsApi[i].name,
        createdAt: needsApi[i].createdAt,
      ));
    }

    return selectedRoles.copyWith(needs: needsRepository);
  }
Run Code Online (Sandbox Code Playgroud)

当我尝试修改 RoleWithNeeds 中的嵌套数组时的部分

FutureOr<void> _onClickNeed(_ClickNeed event, Emitter<NeedState> emit) {
    emit(_Load());

    try {
      for (var role …
Run Code Online (Sandbox Code Playgroud)

flutter flutter-bloc flutter-freezed

5
推荐指数
0
解决办法
3887
查看次数

我想在“Isar”中创建一个“collection”,但遇到了一个完全令人费解的错误并且遇到了麻烦

我想创建一个如下所示的集合,但是当我运行 flutter pub run build_runner build --delete-conflicting-outputs 时,出现以下错误。

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:isar/isar.dart';

part 'model.freezed.dart';
part 'model.g.dart';

@freezed
@Collection(ignore: {'copyWith'}, inheritance: false)
class Model with _$Model {
  const factory Model({
    required String address,
  }) = _Model;
  Id get id => Isar.autoIncrement;
  const Model._();
}
Run Code Online (Sandbox Code Playgroud)

错误:

Constructor parameter does not match a property.
|
| required String address,
|
Run Code Online (Sandbox Code Playgroud)

尽管有一个简单的集合,但我遇到了错误并陷入困境。我该如何解决这个错误?

此外,在生成冻结文件时,不会创建 的.g.文件。Isar

dart flutter flutter-freezed flutter-isar

5
推荐指数
1
解决办法
190
查看次数

使用带有通用类型类的 Freezed 进行反序列化

几个月前引入的反序列化通用类功能被冻结。

我正在尝试遵循文档,但遇到编译时错误:

The argument type 'NameOfClass Function(Map<String, dynamic>)' can't be assigned to the parameter type 'NameOfClass Function(Object?)'.

这是我的数据类的简化版本,用于解释我想要实现的目标。

1. 外部类

@Freezed(genericArgumentFactories: true)
class ResponseWrapper<T> with _$ResponseWrapper<T>{
  const factory ResponseWrapper ({
    final String? Status,
    final T? Response,
  }) = _ResponseWrapper;

  factory ResponseWrapper.fromJson(Map<String, dynamic> json,
      T Function(Object? json) fromJsonT)
    => _$ResponseWrapperFromJson<T>(json, fromJsonT);
}
Run Code Online (Sandbox Code Playgroud)

2. 内部类

@freezed
class NewUser with _$NewUser {
  const factory NewUser({
    String? firstName,
    String? middleName,
    String? surname,
    String? username,
    String? emailId,
  }) = _NewUser;

  factory NewUser.fromJson(Map<String, dynamic> …
Run Code Online (Sandbox Code Playgroud)

generics dart flutter freezed flutter-freezed

3
推荐指数
1
解决办法
2272
查看次数

如何使用冻结忽略空值toJson?

我尝试创建一个这样的轮廓模型;fromJson看起来不错,但我有一个问题toJson:

@Freezed(
  fromJson: true,
  toJson: true,
  map: FreezedMapOptions.none,
  when: FreezedWhenOptions.none,
)
class ProfileAttribute with _$ProfileAttribute {
  const factory ProfileAttribute({
    @JsonKey(name: '_id', includeIfNull: false) final String? id,
    final String? uid,
    final String? username,
    final String? name,
    final String? phone,
    final String? email,
    final String? address,
    final String? image,
  }) = _ProfileAttribute;

  factory ProfileAttribute.fromJson(Map<String, dynamic> json) =>
      _$ProfileAttributeFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

我看到调试 toJson 将发送:

"attributes": {
   "_id": null,
   "uid": null,
   "username": null,
   "name": null,
   "phone": null,
   "email": "asdasda@gmasd.com",
   "address": null, …
Run Code Online (Sandbox Code Playgroud)

flutter flutter-dependencies json-serializable flutter-freezed

3
推荐指数
1
解决办法
2628
查看次数

@freezed copyWith 缺少密封类

在以下代码片段中,state.copyWith 函数不可用。

@freezed
class MyState with _$MyState {
  @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
  const factory MyState({@Default(0) int counter,}) = _MyState;
  const factory MyState.initial({@Default(0) int counter}) = Initial;
  const factory MyState.loading() = Loading;
  const factory MyState.one() = One;
  const factory MyState.two() = Two;

  factory MyState.fromJson(Map<String, dynamic> json) =>
      _$MyStateFromJson(json);
}

class MyStateNotifier extends StateNotifier<MyState> {
  MyStateNotifier() : super(MyState.initial());

  Future<void> one() async {
    state = MyState.loading();
    await Future.delayed(Duration(seconds: 5));
    state.copyWith(counter: 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我删除密封类时,copyWith 函数可用。

@freezed
class MyState with _$MyState {
  @JsonSerializable(fieldRename: FieldRename.snake, …
Run Code Online (Sandbox Code Playgroud)

dart flutter flutter-freezed

2
推荐指数
1
解决办法
5333
查看次数

如何使用 flutter freeze 包在模型中生成日期时间

我有这个冻结的部分

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_model.freezed.dart';
part 'user_model.g.dart';

@freezed
class UserModel with _$UserModel {
  factory UserModel({
    required String id,
    @Default('') String uniqueId,
    @Default(DateTime.now()) DateTime dob,

  }) = _UserModel;

  factory UserModel.fromJson(Map<String, dynamic> json) =>
      _$UserModelFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

但由于DateTime.now() ,我无法生成所需的文件。

如果我做这样的事情:

factory UserModel({
        required String id,
        @Default('') String uniqueId,
        required DateTime dob,
    
      }) = _UserModel;
Run Code Online (Sandbox Code Playgroud)

它会起作用,但我必须手动将生成的数据编辑为:

dob: (json['dob'] as Timestamp?)?.toDate() ?? DateTime.now()
Run Code Online (Sandbox Code Playgroud)

从

dob: DateTime.parse(json['dob'] as String),
Run Code Online (Sandbox Code Playgroud)

我不能一直手动编辑它。

请问如何生成包括日期时间的模型类。

model dart flutter flutter-freezed

1
推荐指数
1
解决办法
3186
查看次数

向冻结类添加方法

我正在使用冻结的包来生成数据类。

该包支持使用注释禁用 copyWith 生成@Freezed(copyWith: false)。

我想对我的冻结数据类实现自定义copyWith。这是我的代码:

@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {
  const factory AuthenticationState({
    String? userId,
    ErrorObject? errorObject,
  }) = _AuthenticationState;

  AuthenticationState copyWith({
    String? userId,
    ErrorObject? errorObject,
  }) {
    return AuthenticationState(
      userId: userId ?? this.userId,
      errorObject: errorObject, // resets if not provided
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

I 代运行成功并且没有静态分析错误。

但是当我运行该应用程序时,我收到此错误:

authentication_bloc.freezed.dart:32:7:错误:非抽象类“_$_AuthenticationState”缺少这些成员的实现:

  • AuthenticationState.copyWith 尝试任一
  • 提供一个实现,
  • 从超类或 mixin 继承实现,
  • 将类标记为抽象类,或者
  • 提供“noSuchMethod”实现。

类 __$_AuthenticationState 实现 _AuthenticationState { ^^^^^^^^^^^^^^^^^^^^^^lib/authentication/bloc/authentication_state.dart:28:23:上下文:'AuthenticationState.copyWith'在这里定义。

问题是什么?如何copyWith在冻结类中实现自定义?

flutter freezed flutter-freezed

0
推荐指数
1
解决办法
2513
查看次数