Hasen
Hasen

Reputation: 12314

Flutter if statement within widget

Not sure why this if statement is not working:

  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          if (text.length > 0) {
             for (var val in text) Center(child: etc..)
            }
        ],
      ),
)

The code within the if statement (removed for now) works fine without the if statement, but as soon as I add it I get the error The element type 'Map' can't be assigned to the list type 'Widget'.

How should I compose this if statement within a widget? I realise it's within a return statement but not sure why the for loop is fine but not the if statement..

Upvotes: 1

Views: 2393

Answers (4)

Ahmed
Ahmed

Reputation: 41

You can change your code to be like this:

if (text.length > 0) ...{
         for (var val in text) Center(child: etc..)
        }

for more info you can check this site: What’s New In Dart 2.3?

Upvotes: 0

Jean-Pierre Schnyder
Jean-Pierre Schnyder

Reputation: 1934

Here's the code if you want the squared value to be inserted after the source value:

  List<int> numbers = [1, 2, 3, 4, 5];

  var includeSquares = true;
  var allWithSquares = [
    for (var n in numbers)
      if (includeSquares) ...[n, n * n],
  ];
  
  print(allWithSquares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]

Same result, but without if statement:

  List<int> numbers = [1, 2, 3, 4, 5];

  var allWithInsertedSquares = [
    for (var n in numbers) ...[n, n * n],
  ];

  print(allWithInsertedSquares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]

Upvotes: 0

Spatz
Spatz

Reputation: 20118

for loop is fine inside collection because it is new Dart feature (starting from version 2.3). For example next snippet generates new list of squares:

  var numbers = [1, 2, 3, 4, 5];
  var squares = [for (var n in numbers) n * n];
  print(squares); // [1, 4, 9, 16, 25]

if inside collection also new for Dart 2.3 and allow filter elements out:

  bool includeZero = false;
  var all = [if (includeZero) 0, 1, 2, 3, 4, 5];
  print(all); // [1, 2, 3, 4, 5]

You can even combine both construction:

  var includeSquares = true;
  var allWithSquares = [
    ...numbers,
    if (includeSquares) for (var n in numbers) n * n
  ];
  print(allWithSquares); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

The only thing you can't do is use curly braces as code blocks inside collections. You still can use curly braces to define Map as element. In your case curly braces gives next result:

  var includeSquares = true;
  var allWithSquares = [
    ...numbers,
    if (includeSquares) {for (var n in numbers) n * n}
  ];
  print(allWithSquares); // [1, 2, 3, 4, 5, {1, 4, 9, 16, 25}]

You can read more about new Dart features here

Upvotes: 6

Filled Stacks
Filled Stacks

Reputation: 4346

You have to remove the curly braces from the if. Then you add curly braces in the list it's interpreted as a map

Upvotes: 1

Related Questions