Dart Setから要素を削除する

Dartで、Setに要素を削除するコードを記述してます。「remove」を使用して削除します。存在しない値を指定した場合は変化はありません。また、「const」で宣言したsetに使用するとエラーとなります。
環境
- OS windows11 home
- Dart 2.18.4
要素を削除
要素を削除するには、「remove」を使用します。
セット.remove(値)
実際に、使用して削除してみます。
void main() {
var set = {'aaa','bbb','ccc'};
set.remove('aaa');
print(set); // {bbb, ccc}
set.remove('bbb');
print(set); // {ccc}
}
実行結果を見ると、削除されていることが確認できます。

存在しない値は指定してもエラーにはならずに、元のsetのままになります。
void main() {
var set = {'aaa','bbb','ccc'};
set.remove('ddd');
print(set); // {aaa, bbb, ccc}
}
定数
「const」で宣言したリストを削除するとエラー「Unsupported operation: Cannot change an unmodifiable set」が発生します。
void main() {
const set = {'aaa','bbb','ccc'};
set.remove('ccc');
print(set);
}
Unhandled exception:
Unsupported operation: Cannot change an unmodifiable set
#0 _UnmodifiableSetMixin._throwUnmodifiable (dart:collection/set.dart:345:5)
#1 _UnmodifiableSetMixin.remove (dart:collection/set.dart:370:33)
#2 main (file:///c:/sample/main.dart:4:7)
#3 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
「final」の場合は、メモリ領域は変更できるためエラーにはなりません。
void main() {
final set = {'aaa','bbb','ccc'};
set.remove('ccc');
print(set); // {aaa, bbb}
}
removeAll
「set」から「set」で指定した値を削除する場合は「removeAll」を使用します。
void main() {
final set = {'aaa','bbb','ccc'};
set.removeAll({'aaa','bbb'});
print(set); // {ccc}
}
-
前の記事
PHPエラー『Warning: Illegal String Offset』の解決方法 2025.04.23
-
次の記事
Reactでのマルチステップフォームの実装方法 2025.04.23
コメントを書く