Home > Blockchain >  The element type 'Set<TableRow>' can't be assigned to the list type 'Table
The element type 'Set<TableRow>' can't be assigned to the list type 'Table

Time:08-06

So I have a function that return a Table Row

TableRow buildRow(List<String> cells, {bool isHeader = false}) => TableRow(
      children: cells.map((cell) {
    final style = TextStyle(
      fontWeight: isHeader ? FontWeight.bold : FontWeight.normal,
      fontSize: 18,
    );

    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: Center(
          child: Text(
        cell,
        style: style,
      )),
    );
  }).toList());

And I want to depict the Table if a certain condition is met:

Table(
                                border: TableBorder.all(),
                                children: [
                                  if (cartController.totalNum(produkt)! <
                                      11)
                                      { buildRow(
                                          ["ab Menge", "Preis pro Stück"],
                                          isHeader: true),}

But I get following error:

The element type 'Set' can't be assigned to the list type 'TableRow'

Without the if statement my code works flawlessly, what can I do?

CodePudding user response:

In this code:

Table(
  border: TableBorder.all(),
  children: [
    if (cartController.totalNum(produkt)! < 11)
      { buildRow(["ab Menge", "Preis pro Stück"], isHeader: true), } 
  ],
),

You are using a collection if, which unlike a standard if statement, does not support using {} to denote the body of the if, instead it supports only a single expression as the body. Additionally, {} (containing comma separated values) is an expression that creates a Set literal in dart. Essentially, you are creating a List<Set<TableRow>> when you want a List<TableRow>. All you need to do is remove the {} so you do not wrap each TableRow in a Set literal.

Table(
  border: TableBorder.all(),
  children: [
    if (cartController.totalNum(produkt)! < 11)
      buildRow(["ab Menge", "Preis pro Stück"], isHeader: true),
  ],
),

CodePudding user response:

Do it like

  if (cartController.totalNum(produkt)! < 11)
            buildRow(["ab Menge", "Preis pro Stück"], isHeader: true),

Others way to handle conditional if

body: Table(
  children: [
    if (1 < 2) buildRow(["ab Menge", "Preis pro Stück"], isHeader: true),
    if (1 < 2 && 3.isEven)
      buildRow(["ab Menge", "Preis pro Stück"], isHeader: true),
    //inline function
    () {
      if (1 == 3)
        return buildRow(["ab Menge", "Preis pro Stück"], isHeader: true);
      else if (1 > 3)
        return buildRow(["ab Menge", "Preis pro Stück"], isHeader: true);
      else
        return buildRow(["ab Menge", "Preis pro Stück"], isHeader: true);
    }()
  ],
  • Related