Dart リスト(配列)の最後の値を削除する

Dart リスト(配列)の最後の値を削除する

Dartで、リスト(配列)から位置を指定して値を削除するコードを記述してます。「removeLast」を使用すると削除できます。また、「removeLast」は範囲外の位置や「const」を指定したリストに対して実行するとエラーが発生します。

環境

  • OS windows11 home
  • Dart 2.18.1

最後の値を削除

最後の値を削除するには「 removeLast 」を使用します。

リスト.removeLast()

※ 削除した値が返ります

実際に使用して、最後にある値を削除してみます。

void main() {
  var list = ['aaa', 'bbb', 'ccc'];

  print(list.removeLast()); // ccc

  print(list); // [aaa, bbb]
}

実行結果を見ると、最後にある値が削除されていることが確認できます。

空のリストに使用するとエラー「RangeError」が発生します。

void main() {
  var list = [];

  print(list.removeLast());

  print(list);
}
Unhandled exception:
RangeError (index): Invalid value: Valid value range is empty: -1
#0      List.[] (dart:core-patch/growable_array.dart:264:36)
#1      List.removeLast (dart:core-patch/growable_array.dart:336:20)
#2      main (file:///c:/sample/main.dart:4:14)
#3      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

定数

「const」で宣言したリストを削除しようとすると、エラー「Unsupported operation: Cannot remove from an unmodifiable list」が発生します。

void main() {
  const list = ['aaa', 'bbb', 'ccc'];

  print(list.removeLast());

  print(list);
}
Unhandled exception:
Unsupported operation: Cannot remove from an unmodifiable list
#0      UnmodifiableListMixin.removeLast (dart:_internal/list.dart:169:5)
#1      main (file:///c:/sample/main.dart:4:14)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

「final」の場合は、メモリ領域は変更できるためエラーにはなりません。

void main() {
  final list = ['aaa', 'bbb', 'ccc'];

  print(list.removeLast()); // ccc

  print(list); // [aaa, bbb]
}

最初の値を削除

最初の値を削除するには「removeAt」で「0」を指定します。

void main() {
  final list = ['aaa', 'bbb', 'ccc'];

  print(list.removeAt(0)); // aaa

  print(list); // [bbb, ccc]
}