9

I have a StatefulWidget widget with a LinkedHashMap member done like this:

LinkedHashMap _items = new LinkedHashMap<String, List<dynamic>>();

Now I need to filter the items inside the List<dynamic> items of the Map.

I use this code to filter:

function filter(_items) {
    return _items.map((day, items) {
        return new MapEntry(day, items.where((i) {
          return i.stringProperty.contains(widget.filter);
        }).toList());
    });
}

But I get the error in the subject

type '(dynamic) => dynamic' is not a subtype of type '(dynamic) => bool' of 'test'

Giacomo M
  • 4,450
  • 7
  • 28
  • 57
  • 1
    Similar problem with Dart version 2.7.2, and the ternary operator trick solves it. I am not even using a function like `contains`, but a straight boolean test (`a>0`). Perhaps some bug or regression somewhere. BTW the `test` is the callback passed to `where`, according to the [language reference](https://api.dart.dev/stable/2.7.2/dart-collection/ListMixin/where.html). – Eric Platon Apr 20 '20 at 06:18

3 Answers3

11

I solved with this code:

function filter(_items) {
    return _items.map((day, items) {
        return new MapEntry(day, items.where((i) {
          return i.stringProperty.contains(widget.filter) ? true : false;
        }).toList());
    });
}

It seems the contains function does not return a bool value.

Giacomo M
  • 4,450
  • 7
  • 28
  • 57
  • 1
    `contains` does indeed return a boolean. Something else is interfering. – Randal Schwartz Dec 16 '19 at 02:06
  • @RandalSchwartz the solution that worked is pretty clear, the problem was the return value of the contains function. I am not able to find out something that interferes. – Giacomo M Dec 16 '19 at 08:44
  • 1
    I resolved it with a similar approach. Using either "? true : false" or "as bool" for contains. Although, curious why it wouldn't accept the result of contains method. As documentation says it should return a bool - https://api.flutter.dev/flutter/dart-core/Iterable/contains.html – GAMA Nov 02 '21 at 05:11
3

I believe this will also work, still not sure why it doesn't return a bool though

function filter(_items) {
    return _items.map((day, items) {
        return new MapEntry(day, items.where((i) {
          return (i.stringProperty.contains(widget.filter)) as bool;
        }).toList());
    });
}
Sunn
  • 766
  • 9
  • 17
0

Where method returns a list, so you don't need to use toList(), and you should specify the return type of map method when you are using it.

  filter(_items) {
    return _items.map<String, List<bool>>((day, items) {
      return MapEntry(
        day, items.where((i) => i.stringProperty.contains(widget.filter)),
      );
    });
  }
dshukertjr
  • 15,244
  • 11
  • 57
  • 94