Search code examples
flutter

How to set a text style to the Datatable?


I'm passing data to a datatable located in the child widget from parent widget. I need to set a textstyle to the text in whole datatable how can I do that?

Child widget

Container(
      child: widget.dataTable,
    )                    

Parent widget

DataTable(headingRowHeight: 0, columns: [
        DataColumn(label: Text(' ')),
        DataColumn(label: Text(' ')),
      ], rows: [
        DataRow(
            cells: [DataCell(Text('John')), DataCell(Text('department1'))])
      ])

Solution

  • Inside DataTable widget, you can find properties called dataTextStyle. Then you can use TextStyle as usual. Example:

    DataTable(
      headingRowHeight: 0,
      // for Heading Text Style
      headingTextStyle: TextStyle(fontSize:14, ...),
      // for Text Style inside Data Rows
      dataTextStyle: TextStyle(fontSize: 12, ...),
      columns:[],
      rows:[],
    ),
    

    You can check here for more advance.

    Instead of setting a style for each DataTable. If you only have a one style and want to applying a custom style to the entire apps, you can set the ThemeData in MaterialApp. Example:

      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            dataTableTheme: DataTableTheme(
              headingTextStyle: ... // put the style here
              dataTextStyle: ... // put the style here
              // There are many styles here that can be customized
            ),
          ),
          home: Scaffold(
            body: Center(
              child: Text('Hello, World!'),
            ),
          ),
        );
      }