why I can't run my code where is the problem of this code?

Viewed 50
void main() {
  const list = [1, 2, 3, 4];
  final odd = where(list, (value) => value % 2 == 1);
  print(odd);
}

List<T> where<T>(List<T> items, bool Function(T) f) {
  var results = <T>[];
  for (var item in items) {
    if (f(item)) {
      results.add(item);
    }
  }
  return results;
}

this kind of error show in my terminal

lib/exercises/18-implement-where-function.dart:3:44: Error: The operator '%' isn't defined for the class 'Object?'.

  • 'Object' is from 'dart:core'.

Try correcting the operator to an existing operator, or defining a '%' operator. final odd = where(list, (value) => value % 2 == 1);

void main() {
  const list = [1, 2, 3, 4];
  final odd = where(list, (value) => value! % 2 == 1);
  print(odd);
}

List<T> where<T>(List<T> items, bool Function(T) f) {
  var results = <T>[];
  for (var item in items) {
    if (f(item)) {
      results.add(item);
    }
  }
  return results;
}

The operator '%' isn't defined for the type 'Object'. Try defining the operator '%'

2 Answers

Possible Dart analyzer is not able to infer type.
It's better to wait for the answer from the developers.

A workaround as below:

void main() {
  const list = [1, 2, 3, 4];
  final odd = where(list, (int value) => value % 2 == 1);
  print(odd);
}

List<T> where<T>(List<T> items, bool Function(T) f) {
  var results = <T>[];
  for (var item in items) {
    if (f(item)) {
      results.add(item);
    }
  }
  return results;
}

P.S.

I also encounter this issue from time to time in Dart.

On the one hand, the type is not explicitly specified (for parameter value) and must be inferred, on the other hand, it is not clear why it is not inferred from another type (aslo T), which is inferred from the value (in our case. list) wuth the same type parameter (T).

I've run your code on https://dartpad.dev/dart, it's working though. I think there is an issue with your import classes.

Related