skip to Main Content

I try to use Expanded in a DataColumn but I got Incorrect use of ParentDataWidget

The idea is, I want to make the text inside the column center.
So I code like below:

    DataColumn(
      label: Expanded(
        child: Center(
          child: Text(
            'Center',
          ),
        ),
      ),
    ),

The only way I can make it is by using Expanded. But it will make me a Incorrect use of ParentDataWidget

So, other than Expanded, how can I make my child widget has the size same as the parent widget, in my case, the DataColumn widget?

Thanks

PS. full code of my DataTable

  Widget getDataTable() {
    return DataTable(
      columns: const [
        DataColumn(
          label: Expanded(
            child: Center(
              child: Text(
                'center 1',
              ),
            ),
          ),
        ),
        DataColumn(
          label: Expanded(
            child: Center(
              child: Text(
                'center 2',
              ),
            ),
          ),
        ),
      ],
      rows: const [
        DataRow(
          cells: [
            DataCell(
              Expanded(
                child: Center(child: Text('centered content')),
              ),
            ),
            DataCell(
              Expanded(
                child: Center(child: Text('centered content 2')),
              ),
            ),
          ],
        ),
      ],
    );
  }

2

Answers


  1. In flutter code snippet, the code you write as is no issue and work well. There may another error? Here is I test and copy from flutter code snippet with DataColumn().

          DataColumn(
              label: Expanded(
                child: Center(
                  child: Container(
                    color:Colors.red,
                    child: const Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ),
              ),
            ),
       
    
    Login or Signup to reply.
  2. DataCell() is made of SizedBox.shrink():

    SizedBox.shrink() : It creates a box that will become as small as its parent allows.

    Expanded() : It tries to occupy all the space available

    So, that’s the reason you are getting error of,

    Incorrect use of ParentDataWidget

    Avoid wrapping DataCell with Expanded:

    DataRow(
                    cells: [
                      DataCell(
                        Text('centered content 1'),
                      ),
                      DataCell(
                        Text('centered content 2'),
                      ),
                    ],
                  ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search