首页 > 解决方案 > Flutter DataTable - how set column width?

问题描述

I use DataTable in my Flutter app. This is simple example of my code:

    DataTable(
          columns: [
            DataColumn(label: Text('Column1')),
            DataColumn(label: Text('Column2')),
            DataColumn(label: Text('Column3')),
          ],
          rows: [
            DataRow(cells: [
              DataCell(Text('1')),
              DataCell(Text('2')),
              DataCell(Text('6')),
            ]),
            DataRow(cells: [
              DataCell(Text('12')),
              DataCell(Text('John')),
              DataCell(Text('9')),
            ]),
          
          ],
        )

I need to:

-column1 to be 20% of the available width

-column1 to be 40% of the available width

-column1 to be 40% of the available width

How can I do this? Is it possible for DataTable?

标签: flutterdartflutter-layout

解决方案


You can try something like this :

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final double width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter Demo"),
      ),
      body: Container(
        width: width,
        child: DataTable(
          columnSpacing: 0,
          horizontalMargin: 0,
          columns: [
            DataColumn(
              label: Container(
                width: width * .2,
                child: Text('Column1'),
              ),
            ),
            DataColumn(
              label: Container(
                width: width * .4,
                child: Text('Column2'),
              ),
            ),
            DataColumn(
              label: Container(
                width: width * .4,
                child: Text('Column3'),
              ),
            ),
          ],
          rows: [
            DataRow(cells: [
              DataCell(Text('1')),
              DataCell(Text('2')),
              DataCell(Text('6')),
            ]),
            DataRow(cells: [
              DataCell(Text('12')),
              DataCell(Text('John')),
              DataCell(Text('9')),
            ]),
          ],
        ),
      ),
    );
  }
}

推荐阅读