Farwa
Farwa

Reputation: 7064

What's the usage of three dots (...) in dart List?

I have my code written like this but it gives an error saying:

Error: A value of type 'List' can't be assigned to a variable of type 'Widget'.

Column(
  children: [
    Question(
      questions[_questionIndex]['questionText'],
    ),
    ...(questions[_questionIndex]['answers'] as List<String>)
        .map((answer) {
      return Answer(_answerQuestion, answer);
    }).toList()
  ],
)

Upvotes: 25

Views: 21136

Answers (4)

هيثم
هيثم

Reputation: 1081

var x = [20,30,40];
var list = [1,2,3,x];

// Using the spread operator, adds the items individually not as a list
var separatedList = [1,2,3,...x];

print(list); // length = 4
print(separatedList); // length = 6

Results

[1, 2, 3, [20, 30, 40]]
[1, 2, 3, 20, 30, 40]

Upvotes: 15

Jitesh Mohite
Jitesh Mohite

Reputation: 34250

Dart 2.3 comes with the spread operator (...) and the null-aware spread operator (...?), which allows us to add multiple elements in Collections.

  List<String> values1 = ['one', 'two', 'three'];
  List<String> values2 = ['four', 'five', 'six'];
  var output = [...values1,...values2];
  print(output); // [one, two, three, four, five, six]

For Flutter, we can use this inside column

   Column(
          children: [
            ...values.map((value) {
              return Text(value);
            }),
          ],
        ),

Output:

enter image description here

Upvotes: 17

Farwa
Farwa

Reputation: 7064

I've figured out my issue. My flutter SDK wasn't upgraded. Ran flutter doctor command and sorted out the missing updates. And the syntax seems to be working fine now.

flutter upgrade

Dart version (required) >= 2.3

Restart IDE (if the problem persists)

Upvotes: 0

Amit Prajapati
Amit Prajapati

Reputation: 14315

Dart 2.3 introduce Spread operator (…)

Reference link : https://medium.com/flutter-community/whats-new-in-dart-2-3-1a7050e2408d

    var a = [0,1,2,3,4];
    var b = [6,7,8,9];
    var c = [...a,5,...b];

    print(c);  // prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 33

Related Questions