I am creating a Map with:
Map<int,List<OverlapParams>> map = new Map<int,List<OverlapParams>>();
And I want to upsert elements to the Map, so like, when Map key 2 is not existing, I want to save a List<OverlapParams>
there. – if the Map key is exisiting, I want to add the item overlapitem
to the List in the map.
Here is my code:
final overlapitem = OverlapParams(childParentData.hashCode.toString(), DateTimeRange(
start: childParentData.startDateTime ?? DateTime(2000),
end: childParentData.endDateTime ?? DateTime(2000),
), {});
int pos = childParentData.position ?? 0;
map.update(
pos,
(existingValue) => (existingValue as List<OverlapParams>).add(overlapitem),
ifAbsent: () => [overlapitem],
);
but I get folowing error with underlined (existingValue as List<OverlapParams>).add(overlapitem)
:
error: The return type 'void' isn't a 'List<OverlapParams>', as required by the closure's context.
I dont understand what void means in this context?
2
Answers
You need to return a value in the map.update function.
List.add(value) does not return anything
try this
I haven’t tested this out, but if existing value is immutable, then try this
The second parameter of the
update
method isV update(V value)
.What does that mean in English? A method that receives a parameter of type V and returns an instance of type V.
Now lets look at what you passed as parameter:
Now, it clearly is a method. It clearly get a parameter. What does it return? Nothing on the first glance. On second look, since you have no explicit return, it returns the result of the expression
(existingValue as List<OverlapParams>).add(overlapitem)
. The result isvoid
, since that is whatadd
returns.So that is why your compiler is complaining: your function is not returning what it is supposed to return.
You can explicitly return something:
If for some reason you want a new list to replace the old one (that is what the update method is meant for), you could return a new list from your anonymous function:
I have removed the
as
part, this should not be neccessary, since yourV
type is already defined to beList<OverlapParams>
.