How to delete a row from a DataTable in Flutter?

Viewed 2471

I'm new to flutter. I'm creating a app with a table which a button in every row. I need to delete the row when that button is pressed.

This is the code of the table.

    DataTable(
      columns: const <DataColumn>[
        DataColumn(label: Text('Medications')),
        DataColumn(label: Text('Amount')),
        DataColumn(label: Text('When')),
        DataColumn(label: Text(' '))
      ],
      rows:
          _data // Loops through dataColumnText, each iteration assigning the value to element
              .map(
                ((element) => DataRow(
                      cells: <DataCell>[
                        DataCell(Text(element[
                            "drug"])), //Extracting from Map element the value
                        DataCell(Text(element["amount"])),
                        DataCell(Text(element["when"])),
                        DataCell(new RButton(
                          id: bid,// bid variable increments by 1 every t
                          onPressed: onPressed,
                        ))
                      ],
                    )),
              )
              .toList(),
    ),

This is the code of RButton

class RButton extends StatelessWidget {
  final int id;
  final Function onPressed;

  const RButton({this.id, this.onPressed});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: 30,
        child: FlatButton(
          onPressed: () {
            onPressed(this.id);
            print(this.id);
          },
          textColor: Colors.red,
          child: Text("-"),
        ));
  }
}

This is the code of the function button run when pressed.

onPressed(id) {
    setState() {
      _data.remove(_data[id]);
    }
  }
1 Answers

Assuming that you are properly using a StatefulWidget to create this example.

setState is a function that takes another function as it's single parameter.

So, it must used like this,

onPressed(id) {
    setState(() {
        _data.remove(_data[id]);
    });
}
Related