flutter Dart冻结了所有构造函数上的同一字段

2jcobegt  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(136)

我正在尝试为我的todo块创建一个状态类,并且希望在开始刷新时保留已加载的todo。有没有更好的方法来做到这一点,基本上在使用冻结包的类的所有构造函数中都有一个相互字段

@freezed
class TodoState with _$TodoState {
  const factory TodoState.loading(List<Todo> todos) = TodoStateLoading;
  const factory TodoState.loaded(List<Todo> todos) = TodoStateLoaded;
  const factory TodoState.error(List<Todo> todos, String message) = TodoStateError;
}

字符串
我已经可以这样使用它了,但我想只调用state.todos,而不必检查它的类型:

TodoState state = TodoStateLoaded([/*example*/]);

state.todos // ERROR
(state as TodoStateLoaded).todos // OK

mefy6pfw

mefy6pfw1#

根据这个注解,冻结不支持超类。最接近的解决方案,可能为您工作是这样的:

// create mixin with getter of properties that you would like to share between states
mixin TodoMixin {
  List<Todo> get todos;
}

@freezed
// add mixin to your class with state
class TodoState with TodoMixin, _$TodoState {
  const TodoState._(); // add private constructor

  //override getter with map function that will return data for each state
  @override
  List<Todo> get todos {
    return map(
      loading: (state) => state.todos,
      loaded: (state) => state.todos,
      error: (state) => state.todos,
    );
  }

  const factory TodoState.loading(List<Todo> todos) = TodoStateLoading;
  const factory TodoState.loaded(List<Todo> todos) = TodoStateLoaded;
  const factory TodoState.error(List<Todo> todos, String message) = TodoStateError;
}

字符串
它将为state创建公共getter,当你引入新的state时,map方法将向你展示,你需要在getter中处理新的状态。在mixin中添加另一个属性,您也需要覆盖它。
要使用它,你可以用肘来称呼它:state.todos;或视图中:context.read<TodoCubit>().state.todos;

nom7f22z

nom7f22z2#

这个用例现在似乎可以开箱即用(freezed: ^2.3.5freezed_annotation: ^2.2.0):

import 'package:freezed_annotation/freezed_annotation.dart';

part 'todo.freezed.dart';

class Todo {}

@freezed
class TodoState with _$TodoState {
  const factory TodoState.loading(List<Todo> noTodos) = TodoStateLoading;
  const factory TodoState.loaded(List<Todo> todos) = TodoStateLoaded;
  const factory TodoState.error(List<Todo> todos, String message) = TodoStateError;
}

void main(List<String> args) {
  const test = TodoState.loading(<Todo>[]);
  test.todos.first;
}

字符串
Freezed将共享工厂参数(这里是List<Todo> todos)定义为_$TodoState mixin的成员。

相关问题