How to condition the display of a Widget list?

Asked

Viewed 112 times

1

I tried to use a if to condition the display of a list of Widgets:

children: <Widget>[
  if (condicao == true) 
  {
    Widget(),
    Widget(),
  }
],

The element type Set < Widget > can’t be Assigned to the list type 'Widget'.

It seems to me that in the design part the flutter does not interpret a {} as a scope as in the Dart pure.

  • 1

    Have you ever tried something like [...] children: condition ? getMyWidgetsArray() : [], [...]? If the problem is just how Dart interprets it, that should solve it. I don’t know Dart, so this is just a pseudocode, I don’t know if this is compatible with language

1 answer

3


You cannot open a new context within a list, in case, open {} in a if or for. But this can be done through operator of spread, or ...:

void main() {
  final insert = true;

  final list = [
    'a',
    if (insert) ...[
      'b',
      'c',
      'd',
    ],
    'e',
  ];

  print(list);
}

Will print:

[a, b, c, d, e]

Example in Dartpad.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.