type '(dynamic) => dynamic' is not a subtype of type '(dynamic) => bool' of 'test' when I use map function
Asked Answered
S

3

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'

Slipshod answered 15/12, 2019 at 11:31 Comment(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.Chlores
S
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.

Slipshod answered 15/12, 2019 at 15:8 Comment(3)
contains does indeed return a boolean. Something else is interfering.Pestiferous
@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.Slipshod
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 - api.flutter.dev/flutter/dart-core/Iterable/contains.htmlPileus
J
4

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());
    });
}
Jaimiejain answered 6/7, 2020 at 8:42 Comment(0)
B
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)),
      );
    });
  }
Buddie answered 15/12, 2019 at 12:52 Comment(2)
shouldn't I return <String, List<dynamic>> instead of <String, List<bool>>?Slipshod
anyway I tried with both bool and dynamic but I still get the error. I am not even able to understand where this error occursSlipshod

© 2022 - 2024 — McMap. All rights reserved.