ivanesi
ivanesi

Reputation: 1663

Can the spread operator be used to supply function arguments?

I'm writing class that extends statelessWidget, its build method returns Text() widget. and I need to pass to it text options (alignment, stile etc.) that came from constructor in Map<dynamic, dynamic>. Why I can't use spread operator like this

final Map textOptions;
final String text;

build(BuildContext context) {
    return Text(text, ...textOptions)
}

Upvotes: 7

Views: 2025

Answers (2)

jamesdlin
jamesdlin

Reputation: 90125

You currently can use the spread operator only for collection literals ([] for List, {} for Map or Set).

From Bob Nystrom's article introducing Dart 2.3's new features:

A spread can only appear in a place that can gracefully handle receiving zero or more values. Without completely overhauling the language’s execution model and turning it into Icon (which I find strangely appealing, but probably not practical…), there aren’t too many places that fit that constraint. Basically collection literals and maybe positional argument lists. (I wrote a proposal for the latter, but it’s quite complex so we aren’t doing it, at least not right now.)

That proposal doesn't quite cover what you want, which is to spread a Map into optional named arguments, however.

Upvotes: 9

Julien Lachal
Julien Lachal

Reputation: 1141

I don't think that the spread operator can be used with something else than List and arrays [1, 2, 3].
Maybe you could first convert your Map to a List and then use the spread operator.

Upvotes: 1

Related Questions