How to update the state when user do something?

431 Views Asked by At

In my code the user can add DataRows to a DataTable. All DataRows are saved in a list. This List I use in a diffrent class where I show the Data of the list. The Problem is that when the user add a Row, the UI doesnt get updated so the user didnt see the new added DataRow. How can i update the UI after the User adds a new DataRow?

class ExerciseTable extends StatefulWidget {
  ExerciseTable({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _ExerciseTableState createState() => _ExerciseTableState();
}

class _ExerciseTableState extends State<ExerciseTable> {
  ExerciseDataSource _rowsDataSource;

  @override
  void initState() {
    _rowsDataSource = ExerciseDataSource(list: _rowList);
    super.initState();
  }

  List<DataRow> _rowList = [
    DataRow(cells: <DataCell>[
      DataCell(Datum(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(ExerciseWidget(key: GlobalKey())),
      DataCell(Notes(key: GlobalKey())),
    ]),
  ];

class ExerciseDataSource extends DataTableSource {
  ExerciseDataSource({Key key, this.list});
  final List<DataRow> list;

  int _selectedCount = 0;

  @override
  int get rowCount => list.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;

  @override
  DataRow getRow(int index) {

    return DataRow.byIndex(
        index: index,
        cells: <DataCell>[
          DataCell(Datum(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(ExerciseWidget(key: GlobalKey())),
          DataCell(Notes(key: GlobalKey())),
        ]);
  }
}
2

There are 2 best solutions below

2
On

TO Update your UI when user do somthing you should use setState method

for more info please check setState

0
On

Firstly, your user have to trigger an event. For exemple, you have GestureDetector widget.
So you can, when user trigger an event, call setState:

GestureDetector(
  onTap:(){
    setState((){
      click++;
    });
  },
)