發生的事情是我有一個名為 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 因為串列是比較的。
但是如果我將它添加到全域類中,它會顯示:
flutter Cannot add to an unmodifiable list
uj5u.com熱心網友回復:
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 你可以做
_drawing.canvasPaths.add(event.canvasPath);
正好
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478287.html
下一篇:如何將整數和字串合并為一個字串?
