冻结的 copyWith 方法不适用于 Union/Sealed 中的 List<T> 模型? (使用 Flutter 和 Freezed 包)

Freezed copyWith method not avaliable for List<T> model in Union/Sealed? (using Flutter with Freezed package)

如何让我的代码(Flutter 使用 Freezed)在此处获取使用“copyWith”冻结功能来更新状态?

冻结Class:

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

part 'todo_list.freezed.dart';
part 'todo_list.g.dart';

@freezed 
class TodoList with _$TodoList {
  const TodoList._();
  factory TodoList({ required List<String> titles }) = _TodoList;
  factory TodoList.loading() = Loading;
  factory TodoList.error([String? message]) = ErrorDetails;

  factory TodoList.fromJson(Map<String, dynamic> json) => _$TodoListFromJson(json);

}

状态通知程序

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:gc_todo/presentation/state/todo_list.dart';
import 'dart:developer' as developer;

final todoListProvider = StateNotifierProvider((ref) => TodoListNotifier());

class TodoListNotifier extends StateNotifier<TodoList> {
  TodoListNotifier() : super( TodoList(titles: ["first", "second"]) );

  void addTodoList(String newTitle) {
    developer.log("addTodoList - $state");
    if (state is List<String>) (List<String> stateToUse) {
      stateToUse.copyWith();  // STILL DOES NOT RECOGNISE "copyWith"
    };
  }

}

Freezed 在联合类型的每个变体周围使用包装类型,在本例中为 TodoList。该类型的“列表”变体并不是您假设的 List<String>

此外,copyWith 仅适用于所有联合变体中定义的属性,在您的情况下是 none。

您应该使用 when 对该类型的所有变体进行“模式匹配”,或者 maybeWhen 仅匹配一个子集。

以下内容应该适用于您的情况:

class TodoListNotifier extends StateNotifier<TodoList> {
  TodoListNotifier() : super( TodoList(titles: ["first", "second"]) );

  void addTodoList(String newTitle) {
    developer.log("addTodoList - $state");
    state.maybeWhen(
        (items) => setState(TodoList(titles: [...items, newTitle]),
        orElse: () { /* TODO */ }
    );
  }

}