如何使用 copyWith 在最终列表中实例化或添加项目?

How to instantiate or add an item in a final List with copyWith?

我有一个 class 名为 Drawing with Equatable 的情况如下:

class Drawing extends Equatable {
  final List<CanvasPath> canvasPaths;

  const Drawing({
    this.canvasPaths = const [],
  });

  @override
  List<Object?> get props => [canvasPaths];

  Drawing copyWith({
    List<CanvasPath>? canvasPaths,
  }) {
    return Drawing(
      canvasPaths: canvasPaths ?? this.canvasPaths,
    );
  }
}

我知道我无法通过以下方式初始化列表本身 canvasPaths = newList; 因为它是 final,但是我使用 copyWith 将它附加到我在以下方式:

class DrawingBloc extends Bloc<DrawingEvent, DrawingState> {

  // Variable global in Bloc, like cached
  final Drawing _drawing = const Drawing();

  DrawingBloc() : super(const DrawingState()) {
    on<StartDrawing>((event, emit) {
      // ! i cant do
      // _drawing.canvasPaths.add(event.canvasPath);
      // ! or
      // _drawing.canvasPaths.last = event.canvasPath;

      // Create a new list
      final newList = _drawing.canvasPaths.toList();

      newList.add(event.canvasPath);

      print(newList);

      _drawing.copyWith(
        canvasPaths: newList,
      ); // using the copyWith but when i print...

      print(_drawing);

      emit(state.copyWith(
        status: DrawingStatus.success,
        currentDrawing: _drawing.canvasPaths,
      ));
    });
  }
}

结果:

我想知道为什么copyWith不显示或不起作用,我不得不说我使用equatable,因为列表是比较的。

但是如果我在全局 class 中添加它,它会显示:

flutter Cannot add to an unmodifiable list

copyWith returns 一个新实例。它不会神奇地将自己变成副本。所以而不是

  print(newList);

  _drawing.copyWith(
    canvasPaths: newList,
  ); // using the copyWith but when i print...

  print(_drawing);

你也许可以

  print(newList);

  var newDrawing = _drawing.copyWith(
    canvasPaths: newList,
  ); // using the copyWith but when i print...

  print(newDrawing);

虽然这可能对您的情况没有帮助。我不熟悉 Equatable 但你做不到吗

this.canvasPaths = [],

而不是

this.canvasPaths = const [],

还是必须是常量?因为如果你离开 const 你可以做

_drawing.canvasPaths.add(event.canvasPath);

很好