Dart エラー「Error: This expression has type ‘void’ and can’t be used.」が発生した場合の対処法

Dart エラー「Error: This expression has type ‘void’ and can’t be used.」が発生した場合の対処法

Dartで、エラー「Error: This expression has type ‘void’ and can’t be used.」が発生した場合の対処法を記述してます。戻り値がないものに対して「print」などを使用した際に発生します。

環境

  • OS windows11 home
  • Dart 2.18.1

エラー全文

以下のコードを実行時に発生。

void main() {
  var list = ['a', 'b', 'c', 'd', 'e'];

  print(list.removeRange(1,2));

  print(list);
}

エラー全文

main.dart:4:14: Error: This expression has type 'void' and can't be used.
  print(list.removeRange(1,2));

原因

「removeRange」の戻り値は「void」なのに「print」を使用しているため

対処法

「print」を使用しないか、

void main() {
  var list = ['a', 'b', 'c', 'd', 'e'];

  list.removeRange(1,2);

  print(list); // [a, c, d, e]
}

範囲を指定して値を取得したいのであれば「sublist」を使用する

void main() {
  var list = ['a', 'b', 'c', 'd', 'e'];

  var list2 = list.sublist(1,2);

  print(list); // [a, b, c, d, e]

  print(list2); // [b]
}