Search code examples
flutterdartflutter-dependencies

How can I use TextField in PaginatedDataTable?


I am writing a simple application where I wanted to use the Table. I want that Table has TextField in cells and now if I write something, it will tell if that value is correct or incorrect. I created a DataTable class.

class VDataTable extends DataTableSource {

  final TextEditingController _controller = TextEditingController();

  @override
  DataRow? getRow(int index) {
    return DataRow(cells: [
      DataCell(
        TextField(
          controller: _controller,
          onSubmitted: (value) {
            if (value.isNotEmpty && value == data[index]["A"].toString()) {
              print('Correct');
            }
          },
        ),
      ),
    ]);
  }

  @override
  // TODO: implement isRowCountApproximate
  bool get isRowCountApproximate => false;

  @override
  // TODO: implement rowCount
  int get rowCount => strVerbsData.length;

  @override
  // TODO: implement selectedRowCount
  int get selectedRowCount => 0;
}

Then in the main file, I am using PaginatedDataTable.

class _MyHomePageState extends State<MyHomePage> {

  final DataTableSource _data = VDataTable();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            PaginatedDataTable(columns: const [
              DataColumn(label: Text("A")),
              DataColumn(label: Text("B")),
            ], source: _data),
          ],
        ),
      ), 
    );
  }
}

Now, issue is that I cannot edit a single cell (TextField). It shows textfield in all the cells and all cells shows same text. Any solution?

Table Fields


Solution

  • Because you only have 1 single TextEditingController. The TextEditingController holds the text for the TextField, if you change now 1 single TextField, all will change.

    You have to create a new TextEditingController for each TextField. So just use a List<TextEditingController> textEditingController.