Navigate trough selected datarows in flutter via arrow down/arrow up

80 views Asked by At

Im currently working on a flutter web project and I want to implement the functionality which allow the user to change selected row inside a DataTable by pressing the keydown and keyup of their keyboard.

I tried by wrapping the DataTable with RawKeyboardListener but this seems not work.

This is the code I used:

var selectedIndex = -1;
RawKeyboardListener(
  focusNode: FocusNode(),
  onKey: (RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
        if (selectedIndex < (snapshot.data!.length - 1)) {
          setState(() {
            selectedIndex++;
          });
        }
      } else if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
        if (selectedIndex > 0) {
          setState(() {
            selectedIndex--;
          });
        }
      }
    }
  },          
  child: DataTable(     
    border: TableBorder.all(color: textColor),
    columnSpacing: 20,
    showCheckboxColumn: false,
    headingRowHeight: 32,
    headingRowColor: MaterialStateColor.resolveWith((states) => mainColor),
    dataRowMinHeight: 40,
    dataRowMaxHeight: 40,
      columns: const <DataColumn>[
        //columns here...
      ],

      rows: List<DataRow>.generate(snapshot.data!.length, (index) {
        final isSelected = index == selectedIndex;
        return DataRow(
          
          selected: isSelected,
          onSelectChanged: (value) {
            setState(() {
              selectedIndex = isSelected ? index : -1;
            });
          },
          cells: <DataCell>[
             // cells here...
            
          ],
        );
      })),
),

Does anyone have a solution?

0

There are 0 answers