25

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()
  ],
)
Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105
Farwa
  • 6,156
  • 8
  • 31
  • 46

4 Answers4

31

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]
Amit Prajapati
  • 13,525
  • 8
  • 62
  • 84
15

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

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
13
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]
هيثم
  • 791
  • 8
  • 11
0

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)

Ranvir
  • 2,094
  • 2
  • 19
  • 26
Farwa
  • 6,156
  • 8
  • 31
  • 46