Проблемы с шириной столбца DataTable - PullRequest
0 голосов
/ 09 мая 2020

Я пытаюсь создать полную ширину DataTable в Flutter с столбцом фиксированной ширины слева и двумя другими столбцами, которые должны разделить оставшиеся с.

Однако, даже если слева текст заголовка усечен, средний и правый столбцы не занимают оставшуюся ширину, как вы можете видеть ниже:

Table screenshot

Я также хотел бы оберните текст в ячейку, если он слишком широк для отображения в одной строке, но Wrap не работает должным образом.

Как я могу решить свои проблемы?

Вот код:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(children: [
          Expanded(
            child: Container(
              constraints: BoxConstraints.expand(width: double.infinity),
              child: SingleChildScrollView(
                child: DataTable(
                    headingRowHeight: 32,
                    dataRowHeight: 24,
                    columns: [
                      DataColumn(
                        label: ConstrainedBox(
                          constraints: BoxConstraints(
                            maxWidth: 20,
                            minWidth: 20,
                          ),
                          child: Text('Short column'),
                        ),
                      ),
                      DataColumn(label: Text('Long column')),
                      DataColumn(label: Text('Long column')),
                    ],
                    rows: [
                      DataRow(
                        cells: [
                          DataCell(
                            ConstrainedBox(
                              constraints: BoxConstraints(
                                maxWidth: 20,
                                minWidth: 20,
                              ),
                              child: Text('1'),
                            ),
                          ),
                          DataCell(
                            Wrap(
                              children: [
                                Text(
                                    """Some long content i would like to be wrapped when column width is not
                              enought to fully display it"""),
                              ],
                            ),
                          ),
                          DataCell(Text('Some more text')),
                        ],
                      ),
                      DataRow(
                        cells: [
                          DataCell(Container(
                            color: Colors.pink,
                            child: ConstrainedBox(
                              constraints: BoxConstraints(
                                maxWidth: 20,
                                minWidth: 20,
                              ),
                              child: Text('2'),
                            ),
                          )),
                          DataCell(
                            Wrap(
                              children: [
                                Container(
                                    color: Colors.yellow,
                                    child: Text(
                                        """Some long content i would like to be wrapped when column width is not
                              enought to fully display it""")),
                              ],
                            ),
                          ),
                          DataCell(Text('Some more text')),
                        ],
                      )
                    ]),
              ),
            ),
          ),
        ]),
      ),
    );
  }
}

EDIT

Спасибо @awaik за ответ, но в вашем примере таблица не занимает всю ширину устройства , он остается посередине с большим экраном, чего я не хотел.

Кроме того, высота строки постоянна, она не увеличивается, если содержание требует большей высоты.

Есть ли что-нибудь, что можно сделать?

Ответы [ 2 ]

1 голос
/ 12 мая 2020

DataTable имеет несколько значений по умолчанию:

DataTable({
  Key key,
  @required this.columns,
  this.sortColumnIndex,
  this.sortAscending = true,
  this.onSelectAll,
  this.dataRowHeight = kMinInteractiveDimension,
  this.headingRowHeight = 56.0,
  this.horizontalMargin = 24.0,
  this.columnSpacing = 56.0,

Ниже фиксированного примера с удаленными виджетами.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: DataTable(
            horizontalMargin: 6.0,
            columnSpacing: 6.0,
            headingRowHeight: 32.0,
            dataRowHeight: 100.0,
            columns: [
              DataColumn(
                label: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: 20,
                    minWidth: 20,
                  ),
                  child: Text('Short column'),
                ),
              ),
              DataColumn(label: Text('Long column')),
              DataColumn(label: Text('Three')),
            ],
            rows: [
              DataRow(
                cells: [
                  DataCell(
                    Text('1'),
                  ),
                  DataCell(
                    Container(
                      child: Text(
                        'Some long content i would like to be wrapped ',
                      ),
                    ),
                  ),
                  DataCell(Text('Some more text')),
                ],
              ),
              DataRow(
                cells: [
                  DataCell(Container(
                    color: Colors.pink,
                    child: Text('2'),
                  )),
                  DataCell(
                      Container(
                        height: 500,
                        color: Colors.yellow,
                        child: Text(
                          'Some long content i would like to be wrapped when column width is not enought to fully display itSome long content i would like to be wrapped when column width is not display it Some long content i would like to be wrapped when column width is not enought to fully display itSome long content i would like to be wrapped when column width is not display it Some long content i would like to be wrapped when column width is not enought to fully display itSome long content i would like to be wrapped when column width is not display it 555',
                        ),
                      ),
                      placeholder: false),
                  DataCell(Text('Some more text')),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

EDIT

  1. Код вверх обновлен.
  2. Таблица не была взята на всю ширину, потому что мы использовали многострочные строки с деревом "" ". Если мы используем обычную строку, поведение нормально.
  3. Высота строки задается в конструкторе и не может быть изменена динамически.

    дочерний элемент: DataTable (horizontalMargin: 6.0, columnSpacing: 6.0, headingRowHeight: 32.0 , dataRowHeight: 100.0,

Наконец, моя личная точка зрения - проще создать свой собственный виджет вместо этого DataTable

enter image description here

0 голосов
/ 17 мая 2020

Я обнаружил, что обычный Table позволяет мне делать то, что я хочу: я могу использовать FixedColumnWidth для определенного столбца и FlexColumnWidth для других, чтобы занять оставшееся место.

Кроме того, текст правильно обернут, а высота строки увеличивается, чтобы соответствовать содержимому, как на изображении ниже, с небольшой шириной экрана и большой шириной экрана:

enter image description here

А это код:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(children: [
          Expanded(
            child: Container(
              child: SingleChildScrollView(
                child: Table(
                  border: TableBorder.all(width: 1),
                  columnWidths: {
                    0: FixedColumnWidth(20),
                  },
                  defaultColumnWidth: FlexColumnWidth(),
                  children: [
                    TableRow(children: [
                      Text('Short column'),
                      Text('Long column'),
                      Text('Long column')
                    ]),
                    TableRow(
                      children: [
                        Text('1'),
                        Text(
                            'Some long content i would like to be wrapped when column width is not enought to fully display it'),
                        Container(
                          child: Text('Some more text'),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        ]),
      ),
    );
  }
}
...