Returning more than one widget using Dart 2.3's collection for

3,211 views
Skip to first unread message

Andrew Brogdon

unread,
Jun 7, 2019, 1:29:05 PM6/7/19
to Flutter Development (flutter-dev)
Not sure if anyone has run into this yet or not, but I'm attempting to do something like:

@override
Widget build(BuildContext context) {
  return Column(
    children: [
      AWidget(),
      SizedBox(height: 10),
      AnotherWidget(),
      for (final record in records) [
        SizedBox(height: 10),
        YetAnotherWidget(record),
      ],
      SizedBox(height: 10),
      FinalWidget(),
    ],
  );
}

The attempt to return an array in the for loop is making the analyzer angry when it tries to flatten everything. Obviously I can convert to use Padding instead of SizedBox in there and make it a single widget for each list record. Does anyone know a way to return two widgets in a Collection-For statement, though?

-Andrew

Bob Nystrom

unread,
Jun 7, 2019, 1:32:31 PM6/7/19
to Flutter Development (flutter-dev)


On Friday, June 7, 2019 at 10:29:05 AM UTC-7, Andrew Brogdon wrote:
The attempt to return an array in the for loop is making the analyzer angry when it tries to flatten everything. Obviously I can convert to use Padding instead of SizedBox in there and make it a single widget for each list record. Does anyone know a way to return two widgets in a Collection-For statement, though?

You're almost there, you just need to use This One Trick Your Doctor Doesn't Want You To Know:

@override
Widget build(BuildContext context) {
  return Column(
    children: [
      AWidget(),
      SizedBox(height: 10),
      AnotherWidget(),
      for (final record in records) ...[
        SizedBox(height: 10),
        YetAnotherWidget(record),
      ],
      SizedBox(height: 10),
      FinalWidget(),
    ],
  );
}

Cheers!

– bob

Andrew Brogdon

unread,
Jun 7, 2019, 1:43:39 PM6/7/19
to Flutter Development (flutter-dev)
Ah, got it. By itself, the for statement is returning a list of two-item lists (List<List<Widget>>), which can't be directly added into a List<Widget>.

Using the spread operator flattens the two-item lists returned by the for statement into one long List<Widget>, though, and it can then be combined with the rest of the outer List's contents.

Thanks! You just saved me some lines of code. :)

-Andrew

Bob Nystrom

unread,
Jun 7, 2019, 2:20:13 PM6/7/19
to Andrew Brogdon, Flutter Development (flutter-dev)
On Fri, Jun 7, 2019 at 10:43 AM 'Andrew Brogdon' via Flutter Development (flutter-dev) <flutt...@googlegroups.com> wrote:
Ah, got it. By itself, the for statement is returning a list of two-item lists (List<List<Widget>>), which can't be directly added into a List<Widget>.

Exactly right. Because you might want to store a collection inside another collection, it doesn't automatically flatten. So you need to use a spread inside the for or if to tell it that's what you want.

Cheers!

– bob

Reply all
Reply to author
Forward
0 new messages