【问题标题】:How to make a multi column Flutter DataTable widget span the full width?如何使多列 Flutter DataTable 小部件跨越整个宽度?
【发布时间】:2019-10-30 16:16:13
【问题描述】:

我有一个 2 列颤动的 DataTable,并且这些行不跨越屏幕宽度,留下大量空白。我发现了这个问题

https://github.com/flutter/flutter/issues/12775

建议将 DataTable 包装在 SizedBox.expand 小部件中,但这不起作用会产生 RenderBox was not laid out:

SizedBox.expand(
                    child: DataTable(columns:_columns, rows:_rows),
            ),

完整的小部件

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body:
      SingleChildScrollView(
      child: Column(
        children: [Container(Text('My Text')),
        Container(
          alignment: Alignment.topLeft,
          child: SingleChildScrollView(scrollDirection: Axis.horizontal,
            child: SizedBox.expand(
                        child: DataTable(columns:_columns, rows:_rows),
                ),
          ),
        ),
      ]))
    );
  }

【问题讨论】:

  • SizedBox.expand 的父级是什么?你能添加你的构建方法吗
  • @diegoveloper 它是 SingleChildScrollView 的子级,它是 Container 的子级
  • @Eugene 我已将完整的小部件代码添加到原始帖子中

标签: flutter dart flutter-layout


【解决方案1】:

您可以将crossAxisAlignmentColumn 添加到strech

crossAxisAlignment: CrossAxisAlignment.stretch

【讨论】:

  • 这会使列拉伸,但不需要 DataTable 小部件随之拉伸。它似乎在 DataTable 本身中固有地受到限制。
  • @user1961 适合我
【解决方案2】:

SizedBox.expand 导致DataTable 采用SingleChildScrollView 不喜欢的无限高度。由于您只想跨越父级的宽度,您可以使用LayoutBuilder 来获取您关心的父级的大小,然后将DataTable 包装在ConstrainedBox 中。

Widget build(BuildContext context) {
  return Scaffold(
    body: LayoutBuilder(
      builder: (context, constraints) => SingleChildScrollView(
        child: Column(
          children: [
            const Text('My Text'),
            Container(
              alignment: Alignment.topLeft,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: ConstrainedBox(
                  constraints: BoxConstraints(minWidth: constraints.minWidth),
                  child: DataTable(columns: [], rows: []),
                ),
              ),
            ),
          ],
        ),
      ),
    ),
  );
}

【讨论】:

  • 谢谢!像魅力一样工作!我给你大拇指。 :)
  • 在我的情况下,我必须将 constraints.minWidth 更改为 constraints.maxWidth 并删除 ScrollViews 才能做到这一点
【解决方案3】:

这是一个问题,不完整,在一个漂亮的小部件中,它是 DataTable, 我在生产代码中遇到了这个问题,这个解决方案适用于一半以上的实验室设备:

ConstrainedBox(
        constraints: BoxConstraints.expand( 
                  width: MediaQuery.of(context).size.width
        ),
child: DataTable( // columns and rows.),)

但是您知道在 %100 的设备上的惊人效果吗?这个:

Row( // a dirty trick to make the DataTable fit width
      children: <Widget>[ 
        Expanded(
          child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: DataTable(...) ...]//row children

注意:Row 只有一个子 Expanded,它依次包含一个 SingleChildScrollView,后者又包含 DataTable。

请注意,这样你可以t use SingleChileScrollView with scrollDirection: Axis.horizontal, in case you need it, but you dont 否则这个问题将与你的用例无关。

如果 Flutter 团队有人看到这里,请丰富 DataTable Widget,它将使 Flutter 具有竞争力和强大,如果做得好,flutter 可能会超越 androids 自己的原生 API。

【讨论】:

  • 第二个超级棒,也可以和ScrollBar一起使用。刚刚发布了我的应用程序,没有在平板电脑上进行测试。让我太兴奋了。现在更新正在进行中!
  • “否则这个问题将无关紧要......”不一定。我需要水平滚动来使 UI 响应,当视图区域很宽时占据整个宽度,当它很窄时可以滚动。
【解决方案4】:

对于 DataTable 小部件,此代码对我有用,因为 dataTable 宽度与设备宽度匹配,

代码 sn-p:

ConstrainedBox(
constraints: 
BoxConstraints.expand(
   width: MediaQuery.of(context).size.width
),
child: 
DataTable(
    // inside dataTable widget you must have columns and rows.),)

您可以使用类似属性删除列之间的空格

 columnSpacing: 0,

注意:

使用 ConstrainedBox 小部件可以解决您的问题,

constraints: BoxConstraints.expand(width: MediaQuery.of(context).size.width),

完整代码:

注意: 在此示例代码中,我介绍了 排序编辑 DataTable 小部件概念。

在 Lib 文件夹中你必须有这个类

  1. main.dart
  2. DataTableDemo.dart
  3. customer.dart

ma​​in.dart 类代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'DataTableDemo.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DataTableDemo(),
    );
  }
}

DataTableDemo.dart 类代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'customer.dart';

class DataTableDemo extends StatefulWidget {
  DataTableDemo() : super();
  final String title = "Data Table";

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

class DataTableDemoState extends State<DataTableDemo> {
  List<customer> users;
  List<customer> selectedUsers;
  bool sort;
  TextEditingController _controller;
  int iSortColumnIndex = 0;
  int iContact;

  @override
  void initState() {
    sort = false;
    selectedUsers = [];
    users = customer.getUsers();


    _controller = new TextEditingController();

    super.initState();
  }

  onSortColum(int columnIndex, bool ascending) {
    if (columnIndex == 0) {
      if (ascending) {
        users.sort((a, b) => a.firstName.compareTo(b.firstName));
      } else {
        users.sort((a, b) => b.firstName.compareTo(a.firstName));
      }
    }
  }

  onSelectedRow(bool selected, customer user) async {
    setState(() {
      if (selected) {
        selectedUsers.add(user);
      } else {
        selectedUsers.remove(user);
      }
    });
  }

  deleteSelected() async {
    setState(() {
      if (selectedUsers.isNotEmpty) {
        List<customer> temp = [];
        temp.addAll(selectedUsers);
        for (customer user in temp) {
          users.remove(user);
          selectedUsers.remove(user);
        }
      }
    });
  }

  SingleChildScrollView dataBody() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: ConstrainedBox(
        constraints: BoxConstraints.expand(width: MediaQuery.of(context).size.width),
        child: DataTable(
          sortAscending: sort,
          sortColumnIndex: iSortColumnIndex,
          columns: [
            DataColumn(
                label: Text("FIRST NAME"),
                numeric: false,
                tooltip: "This is First Name",
                onSort: (columnIndex, ascending) {
                  setState(() {
                    sort = !sort;
                  });
                  onSortColum(columnIndex, ascending);
                }),
            DataColumn(
              label: Text("LAST NAME"),
              numeric: false,
              tooltip: "This is Last Name",
            ),
            DataColumn(label: Text("CONTACT NO"), numeric: false, tooltip: "This is Contact No")
          ],
          columnSpacing: 2,
          rows: users
              .map(
                (user) => DataRow(
                    selected: selectedUsers.contains(user),
                    onSelectChanged: (b) {
                      print("Onselect");
                      onSelectedRow(b, user);
                    },
                    cells: [
                      DataCell(
                        Text(user.firstName),
                        onTap: () {
                          print('Selected ${user.firstName}');
                        },
                      ),
                      DataCell(
                        Text(user.lastName),
                      ),
                      DataCell(Text("${user.iContactNo}"),
                          showEditIcon: true, onTap: () => showEditDialog(user))
                    ]),
              )
              .toList(),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
//          verticalDirection: VerticalDirection.down,
          children: <Widget>[
            Expanded(
              child: Container(
                child: dataBody(),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.all(20.0),
                  child: OutlineButton(
                    child: Text('SELECTED ${selectedUsers.length}'),
                    onPressed: () {},
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(20.0),
                  child: OutlineButton(
                    child: Text('DELETE SELECTED'),
                    onPressed: selectedUsers.isEmpty ? null : () => deleteSelected(),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void showEditDialog(customer user) {
    String sPreviousText = user.iContactNo.toString();
    String sCurrentText;
    _controller.text = sPreviousText;

    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Edit Contact No"),
          content: new TextFormField(
            controller: _controller,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(labelText: 'Enter an Contact No'),
            onChanged: (input) {
              if (input.length > 0) {
                sCurrentText = input;
                iContact = int.parse(input);
              }
            },
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text("Save"),
              onPressed: () {
                setState(() {
                  if (sCurrentText != null && sCurrentText.length > 0) user.iContactNo = iContact;
                });
                Navigator.of(context).pop();
              },
            ),
            new FlatButton(
              child: new Text("Cancel"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

customer.dart 类代码

class customer {
  String firstName;
  String lastName;
  int iContactNo;

  customer({this.firstName, this.lastName,this.iContactNo});

  static List<customer> getUsers() {
    return <customer>[
      customer(firstName: "Aaryan", lastName: "Shah",iContactNo: 123456897),
      customer(firstName: "Ben", lastName: "John",iContactNo: 78879546),
      customer(firstName: "Carrie", lastName: "Brown",iContactNo: 7895687),
      customer(firstName: "Deep", lastName: "Sen",iContactNo: 123564),
      customer(firstName: "Emily", lastName: "Jane", iContactNo: 5454698756),
    ];
  }
}

【讨论】:

    【解决方案5】:

    Container 中设置您的 datatable 并使容器的 widthdouble.infinity

    Container(
        width: double.infinity,
        child: DataTable(
          columns: _columns,
          rows: _rows,
        ));
    

    【讨论】:

      【解决方案6】:

      只需用定义了固定宽度的容器包装数据表,一切都应该正常工作

      即使您需要在一个屏幕中显示多个表格,这对我来说也很有效,从 Flutter 2.2.3 开始。

      final screenWidth = MediaQuery.of(context).size.width;
      Scaffold(
        body: SingleChildScrollView(child:Container(
          child: Column(
            children: [
              Container(
                  width: screenWidth, // <- important for full screen width
                  padding: EdgeInsets.fromLTRB(0, 2, 0, 2),
                  child: buildFirstTable() // returns a datatable
              ),
              Container(
                  width: screenWidth, // <- this is important
                  padding: EdgeInsets.fromLTRB(0, 2, 0, 2),
                  child: buildSecondTable() // returns a datatable
              )
          ])
        ))
      )
      

      这也适用于单表,只需用所需宽度的容器包装。

      【讨论】:

        猜你喜欢
        • 2014-01-27
        • 2020-08-30
        • 1970-01-01
        • 2019-04-18
        • 2010-10-07
        • 2020-11-02
        • 2021-05-26
        • 2014-03-09
        • 2017-04-09
        相关资源
        最近更新 更多