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

问题描述 投票:0回答:2

发生的事情是我有一个名为 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,
      ));
    });
  }
}

结果:

enter image description here

我想知道为什么

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

但是如果我将其添加到全局类中,它会显示以下内容:

flutter Cannot add to an unmodifiable list

list flutter dart final bloc
2个回答
1
投票

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

  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 吗?因为如果你离开 cons 你可以做

_drawing.canvasPaths.add(event.canvasPath);

还好


0
投票

只需将现有列表和其中的新项目传递给 copywith 方法

MyModel updatedModel = myModel.copyWith(
  items: [...myModel.items, 'newItem'],
);

或者如果您想更新特定索引上列表内的值,您可以使用级联运算符...

MyModel updatedModel = myModel.copyWith(
        items: List<String?>.from(myModel.items)..[index] = item);
© www.soinside.com 2019 - 2024. All rights reserved.