eHarazi
eHarazi

Reputation: 418

Spread operator and toList for Map lazy loading in Flutter

I am trying to better understand Dart data structures to use in Flutter. When using a map() to turn a list into widgets, I have seen that you add toList() at the end because map() uses lazy loading and only iterates when it needs to. However, I have also seen that using a spread operator[...] also does the trick.

Going off this SO post, I wanted to know what the best practice is in these situations.

My code is long so I have produced a similar workable example below. I need to use spread operator to create the ElevatedButton's inside Column, but code works with and without toList().

Do I use toList() or is the only purpose for including it is to achieve the same thing the spread operator is already doing?

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var answers = [
      'Answer 1',
      'Answer 2',
      'Answer 3',
    ];
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('My example'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text('The Question',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    )),
                ...answers.map(((e) => CustomButton(e)))
                // .toList()                                 // should this be included?
              ],
            ),
          )),
    );
  }
}

class CustomButton extends StatelessWidget {
  final String anAnswer;

  CustomButton(this.anAnswer);

  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: Text(anAnswer),
    );
  }
}

Upvotes: 0

Views: 547

Answers (1)

Randal Schwartz
Randal Schwartz

Reputation: 44081

I'd simply replace your final children element as:

children: [
            Text('The Question',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                )),

             for (final e in answers) CustomButton(e),
  ],

which uses a list literal for-loop to build the elements. No need for a spread operator as you are inserting the elements directly into the outer list.

Upvotes: 5

Related Questions