3

I have a problem with DataTable in flutter. I want to change the state of the row, when the user click on one of them, but I found just how to do this "manually" with selected: true, inside DataRow.

How can I let the user select just a single row, and deselect the rest, by changing the state?

content: Column(
               children: <Widget>[
                 DataTable(
                   columns: [
                     DataColumn(label: Text('Language')),
                     DataColumn(label: Text('Translation')),
                   ],
                   rows: [
                     DataRow(selected: true, cells: [
                       DataCell(
                         Text(
                           "RO",
                           textAlign: TextAlign.left,
                           style: TextStyle(fontWeight: FontWeight.bold),
                         ),
                         onTap: () {
                           setState(() {
                             color = Colors.lightBlueAccent;

                           });
                         },
                       ),
                       DataCell(
                         TextField(
                           decoration: InputDecoration(
                               border: InputBorder.none, hintText: 'paine'),
                         ),
                       ),
                     ]),
                     DataRow(cells: [
                       DataCell(
                           Text(
                             "EN",
                             textAlign: TextAlign.left,
                             style: TextStyle(fontWeight: FontWeight.bold),
                           ), onTap: () {
                         print('EN is clicked');
                       }),
                       DataCell(
                         TextField(
                           decoration: InputDecoration(
                               border: InputBorder.none, hintText: 'bread'),
                         ),
                       ),
                     ]),
                     DataRow(cells: [
                       DataCell(
                           Text(
                             "FR",
                             textAlign: TextAlign.left,
                             style: TextStyle(fontWeight: FontWeight.bold),
                           ), onTap: () {
                         print('FR is clicked');
                       }),
                       DataCell(
                         TextField(
                           decoration: InputDecoration(
                               border: InputBorder.none, hintText: 'pain'),
                         ),
                       ),
                     ]),
                   ],
                 ),
               ],
             ),

3 Answers 3

9

You can copy past run full code below
You can use condition in selected like this 0 == selectedIndex where 0 is DataRow index
and change selectedIndex in onSelectChanged
code snippet

    int selectedIndex = -1;
    ... 
    rows: [
    DataRow(
        selected: 0 == selectedIndex,
        onSelectChanged: (val) {
          setState(() {
            selectedIndex = 0;
          });
        },
        ...
    DataRow(
        selected: 1 == selectedIndex,
        onSelectChanged: (val) {
          setState(() {
            selectedIndex = 1;
          });
        },

working demo

enter image description here

full code

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Color color;
  int selectedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            DataTable(
              onSelectAll: (val) {
                setState(() {
                  selectedIndex = -1;
                });
              },
              columns: [
                DataColumn(label: Text('Language')),
                DataColumn(label: Text('Translation')),
              ],
              rows: [
                DataRow(
                    selected: 0 == selectedIndex,
                    onSelectChanged: (val) {
                      setState(() {
                        selectedIndex = 0;
                      });
                    },
                    cells: [
                      DataCell(
                        Text(
                          "RO",
                          textAlign: TextAlign.left,
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        onTap: () {
                          setState(() {
                            color = Colors.lightBlueAccent;
                          });
                        },
                      ),
                      DataCell(
                        TextField(
                          decoration: InputDecoration(
                              border: InputBorder.none, hintText: 'paine'),
                        ),
                      ),
                    ]),
                DataRow(
                    selected: 1 == selectedIndex,
                    onSelectChanged: (val) {
                      setState(() {
                        selectedIndex = 1;
                      });
                    },
                    cells: [
                      DataCell(
                          Text(
                            "EN",
                            textAlign: TextAlign.left,
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ), onTap: () {
                        print('EN is clicked');
                      }),
                      DataCell(
                        TextField(
                          decoration: InputDecoration(
                              border: InputBorder.none, hintText: 'bread'),
                        ),
                      ),
                    ]),
                DataRow(
                    selected: 2 == selectedIndex,
                    onSelectChanged: (val) {
                      setState(() {
                        selectedIndex = 2;
                      });
                    },
                    cells: [
                      DataCell(
                          Text(
                            "FR",
                            textAlign: TextAlign.left,
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ), onTap: () {
                        print('FR is clicked');
                      }),
                      DataCell(
                        TextField(
                          decoration: InputDecoration(
                              border: InputBorder.none, hintText: 'pain'),
                        ),
                      ),
                    ]),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

When I needed to call something when I pressed on the DataRow I did the following:

DataRow(
onSelectChanged(_) {
// do something here
}
cells: [],
),

Maybe this will help?

EDIT: this is a simple example of how to select/deselect rows

import 'package:flutter/material.dart';

class Stack1 extends StatefulWidget {
  @override
  _Stack1State createState() => _Stack1State();
}

class _Stack1State extends State<Stack1> {
  bool row1Selected = false;
  bool row2Selected = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: DataTable(
        columns: [
          DataColumn(
            label: Text('My Data'),
          ),
        ],
        rows: [
          DataRow(
            selected: row1Selected,
            onSelectChanged: (value) {
              setState(() {
                row1Selected = value;
              });
            },
            cells: [
              DataCell(
                Text('Data 1'),
              ),
            ],
          ),
          DataRow(
            selected: row2Selected,
            onSelectChanged: (value) {
              setState(() {
                row2Selected = value;
              });
            },
            cells: [
              DataCell(
                Text('Data 2'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

2 Comments

And how could I change the "selected" mode inside the method? Or to change the color of the DataRow, anything would be useful..
@AlexandruBuruiana I'm not sure at the moment, I'll try to find a solution right now.
0
      DataTable(
        dataTextStyle: TextStyle(
          fontSize: 12,
        ),
        headingTextStyle: TextStyle(fontSize: 12),
        dataRowHeight: 100,
        decoration: BoxDecoration(
          color: Constants.backgroundColor,
          borderRadius: BorderRadius.circular(20),
          // border: Border.all(color: Colors.black),
          boxShadow: [
            BoxShadow(
              color: Colors.grey,
              spreadRadius: 2,
              blurRadius: 2,
              offset: Offset(1, 1),
            ),
          ],
        ),
        dividerThickness: 2,
        showCheckboxColumn: false,
        onSelectAll: (value) {},
        columns: [
          DataColumn(
              label: Text(
            'Unit No.',
            style: TextStyle(
                fontWeight: FontWeight.bold, color: Constants.appColor2),
          )),
          DataColumn(
              label: Text(
            'Unit Type',
            style: TextStyle(
                fontWeight: FontWeight.bold, color: Constants.appColor2),
          )),
          DataColumn(
              label: Text(
            'Description',
            style: TextStyle(
                fontWeight: FontWeight.bold, color: Constants.appColor2),
          )),
        ],
        rows: List.generate(
          data.length,
          (index) => DataRow(
              selected: selectedUnit == index,
              onSelectChanged: (value) {
                print(value);
                setState(() {
                  selectedUnit = index;
                  unitNumber = data[index].unitId;
                });

                PersistentNavBarNavigator.pushNewScreen(context,
                    screen: ShowProductDetails(
                      unitId: data[index].unitId,
                    ));
              },
              cells: [
                DataCell(Text(
                  data[index].unitId,
                  style: TextStyle(
                    color: Constants.matGold,
                  ),
                )),
                DataCell(Text(
                  data[index].unitType,
                  style: TextStyle(
                    color: Constants.peach,
                  ),
                )),
                DataCell(Text(
                  data[index].decription,
                  style: TextStyle(
                    color: Constants.appColor,
                  ),
                )),
              ]),
        ),
      ),

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Also, consider making it as simple as possible: remove all formatting containers and attributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.