jayesh saha
jayesh saha

Reputation: 351

Change color of alternate rows of a data table in flutter

Here is my code

class Reference extends StatefulWidget {
  @override
  _ReferenceState createState() => _ReferenceState();
}

class _ReferenceState extends State<Reference> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: ListView(
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: DataTable(
                dataRowHeight: 30,
                dividerThickness: 1.0,
                columnSpacing: 30,
                columns: [
                  DataColumn(
                      label: Text('ID',
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold))),
                  DataColumn(
                      label: Text('Parameter',
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold))),
                 
                rows: [
                  DataRow(cells: [
                    DataCell(Text('1')),
                    DataCell(Text('a')),
                  ]),
                  DataRow(cells: [
                    DataCell(Text('2')),
                    DataCell(Text('b')),
                  ]),
                  DataRow(cells: [
                    DataCell(Text('15')),
                    DataCell(Text('c')),
                  ]),
                ],
              ),
            ),
            Divider(
              height: 5,
              thickness: 5,
            ),
            
 ],
        ));
  }
}

My table is 50 rows long. I am not using a constructor as The data is predetermined and different in each row. How do I color my alternate rows? Do I have to set the color of each DataRow individually or is there a way to do it automatically? I searched and the solutions that I got all work with constructors for creating rows.

For example I found this on flutter api

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatefulWidget(),
      ),
    );
  }
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

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

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  static const int numItems = 10;
  List<bool> selected = List<bool>.generate(numItems, (index) => false);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: DataTable(
        columns: const <DataColumn>[
          DataColumn(
            label: Text('Number'),
          ),
        ],
        rows: List<DataRow>.generate(
          numItems,
          (index) => DataRow(
            color: MaterialStateProperty.resolveWith<Color>(
                (Set<MaterialState> states) {
              // All rows will have the same selected color.
              if (states.contains(MaterialState.selected))
                return Theme.of(context).colorScheme.primary.withOpacity(0.08);
              // Even rows will have a grey color.
              if (index % 2 == 0) return Colors.grey.withOpacity(0.3);
              return null; // Use default value for other states and odd rows.
            }),
            cells: [DataCell(Text('Row $index'))],
            selected: selected[index],
            onSelectChanged: (bool value) {
              setState(() {
                selected[index] = value;
              });
            },
          ),
          ),
        ),
      );
    }
  }

which works with constructor

Upvotes: 2

Views: 3415

Answers (1)

jayesh saha
jayesh saha

Reputation: 351

Finally found a way!

I created a class and a corresponding list of that class to contain all the data of the table. Then I used the constructor method I mentioned in the question to do it.

Final Code

rows: List<DataRow>.generate(
                    ReferenceList.length,
                    (index) => DataRow(
                            color: MaterialStateProperty.resolveWith<Color>(
                                (Set<MaterialState> states) {
                              // Even rows will have a grey color.
                              if (index % 2 == 0)
                                return Colors.pinkAccent.withOpacity(0.3);
                              return null; // Use default value for other states and odd rows.
                            }),
                            cells: [
                              DataCell(Center(
                                  child: Text(ReferenceList[index].id))),
                              DataCell(Center(
                                  child: Text(
                                      ReferenceList[index].parameter))),
                              DataCell(Center(
                                  child: Text(ReferenceList[index]
                                      .refValu1))),
                              DataCell(Center(
                                  child: Text(ReferenceList[index]
                                      .refVal2))),
                            ])),

Upvotes: 5

Related Questions