Flutter 初识:数据表格和卡片

Table

Table 是 Flutter 中用于显示表格布局的小部件。它允许你定义行和列,并为每个单元格指定内容。

属性解析

Table({
    super.key,
    this.children = const <TableRow>[],
    this.columnWidths,
    this.defaultColumnWidth = const FlexColumnWidth(),
    this.textDirection,
    this.border,
    this.defaultVerticalAlignment = TableCellVerticalAlignment.top,
    this.textBaseline, // NO DEFAULT: we don't know what the text's baseline should be
  }) 
  • children (List): 表格的行列表,每一行由多个 TableCell 组成。
  • columnWidths (Map<int, TableColumnWidth>?): 每列的宽度,可以通过列索引指定不同的宽度类型。
  • defaultColumnWidth (TableColumnWidth): 默认的列宽,默认为 FlexColumnWidth(),即均匀分配空间。
  • textDirection (TextDirection?): 文本方向,用于处理文本对齐方式。
  • border (TableBorder?): 表格的边框样式。
  • defaultVerticalAlignment (TableCellVerticalAlignment): 单元格的垂直对齐方式,默认为 TableCellVerticalAlignment.top。
  • textBaseline (TextBaseline?): 基线对齐,用于确保文本基线在同一行内对齐。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Table Example'),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Table(
              border: TableBorder.all(color: Colors.black),
              defaultColumnWidth: FixedColumnWidth(100.0),
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              children: [
                TableRow(children: [
                  TableCell(child: Center(child: Text('Header 1'))),
                  TableCell(child: Center(child: Text('Header 2'))),
                  TableCell(child: Center(child: Text('Header 3'))),
                ]),
                TableRow(children: [
                  TableCell(child: Center(child: Text('Row 1 - Cell 1'))),
                  TableCell(child: Center(child: Text('Row 1 - Cell 2'))),
                  TableCell(child: Center(child: Text('Row 1 - Cell 3'))),
                ]),
                TableRow(children: [
                  TableCell(child: Center(child: Text('Row 2 - Cell 1'))),
                  TableCell(child: Center(child: Text('Row 2 - Cell 2'))),
                  TableCell(child: Center(child: Text('Row 2 - Cell 3'))),
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

在这里插入图片描述

TableRow

TableRow 是 Flutter 中用于定义 Table 的行的小部件。它包含了行的装饰和子小部件

属性解析
TableRow({ this.key, this.decoration, this.children = const <Widget>[]})
  • key (LocalKey?): 唯一标识符,用于在树中标识该行。
  • decoration (Decoration?): 行的装饰,如背景颜色、边框等。
  • children (List): 行中的单元格(即子小部件),默认为空列表。

TableCell

TableCell 是 Flutter 中用于定义 TableRow 中单元格的小部件。它包含了单元格的对齐方式和显示内容。

属性解析
const TableCell({
    super.key,
    this.verticalAlignment,
    required super.child,
  })
  • key (LocalKey?): 唯一标识符,用于在树中标识该单元格。
  • verticalAlignment (TableCellVerticalAlignment?): 单元格的垂直对齐方式,可以是 top、middle、bottom 或 baseline 等。
  • child (Widget): 单元格中显示的小部件,通常是一个文本小部件。

 
 

DataTable

DataTable 是 Flutter 中用于展示数据表格的小部件,通常用于显示大量结构化的数据。

属性解析

DataTable({
    super.key,
    required this.columns,
    this.sortColumnIndex,
    this.sortAscending = true,
    this.onSelectAll,
    this.decoration,
    this.dataRowColor,
    @Deprecated(
      'Migrate to use dataRowMinHeight and dataRowMaxHeight instead. '
      'This feature was deprecated after v3.7.0-5.0.pre.',
    )
    double? dataRowHeight,
    double? dataRowMinHeight,
    double? dataRowMaxHeight,
    this.dataTextStyle,
    this.headingRowColor,
    this.headingRowHeight,
    this.headingTextStyle,
    this.horizontalMargin,
    this.columnSpacing,
    this.showCheckboxColumn = true,
    this.showBottomBorder = false,
    this.dividerThickness,
    required this.rows,
    this.checkboxHorizontalMargin,
    this.border,
    this.clipBehavior = Clip.none,
  })
  • columns (List): 表头列的配置,每个 DataColumn 定义一列的标题和排序行为等。
  • sortColumnIndex (int?): 当前排序列的索引。
  • sortAscending (bool): 是否按升序排序,默认为 true。
  • onSelectAll (Function(bool?)?): “全选” 复选框的回调。
  • decoration (Decoration?): 表格的装饰,如背景颜色、边框等。
  • dataRowColor (MaterialStateProperty<Color?>?): 数据行的背景颜色。
  • dataRowMinHeight (double?): 数据行的最小高度。
  • dataRowMaxHeight (double?): 数据行的最大高度。
  • dataTextStyle (TextStyle?): 数据单元格的文本样式。
  • headingRowColor (MaterialStateProperty<Color?>?): 表头行的背景颜色。
  • headingRowHeight (double?): 表头行的高度。
  • headingTextStyle (TextStyle?): 表头单元格的文本样式。
  • horizontalMargin (double?): 表格水平方向上的间距。
  • columnSpacing (double?): 列之间的间距。
  • showCheckboxColumn (bool): 是否显示选择框列,默认为 true。
  • showBottomBorder (bool): 是否显示底部边框,默认为 false。
  • dividerThickness (double?): 分隔线的厚度。
  • rows (List): 数据行的配置,每个 DataRow 包含多个 DataCell。
  • checkboxHorizontalMargin (double?): 复选框的水平间距。
  • border (TableBorder?): 表格的边框样式。
  • clipBehavior (Clip): 设置裁剪行为,默认为 Clip.none。

示例

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _sortAscending = true;
  int? _sortColumnIndex;

  List<User> _users = [
    User('Alice', 25),
    User('Bob', 30),
    User('Charlie', 35),
  ];

  void _sort<T>(Comparable<T> Function(User user) getField, int columnIndex,
      bool ascending) {
    _users.sort((a, b) {
      if (!ascending) {
        final User c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('DataTable Example'),
        ),
        body: SingleChildScrollView(
          child: DataTable(
            sortColumnIndex: _sortColumnIndex,
            sortAscending: _sortAscending,
            columns: [
              DataColumn(
                label: Text('Name'),
                onSort: (int columnIndex, bool ascending) => _sort<String>(
                    (User user) => user.name, columnIndex, ascending),
              ),
              DataColumn(
                label: Text('Age'),
                numeric: true,
                onSort: (int columnIndex, bool ascending) =>
                    _sort<num>((User user) => user.age, columnIndex, ascending),
              ),
            ],
            rows: _users.map((User user) {
              return DataRow(cells: [
                DataCell(Text(user.name)),
                DataCell(Text('${user.age}')),
              ]);
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class User {
  User(this.name, this.age);

  final String name;
  final int age;
}

在这里插入图片描述

DataColumn

DataColumn 是 Flutter 中用于定义 DataTable 表头列的小部件。它包含了列的标题、提示信息、是否为数字列以及排序等功能。

属性解析
const DataColumn({
    required this.label,
    this.tooltip,
    this.numeric = false,
    this.onSort,
    this.mouseCursor,
  })
  • label (Widget): 用于显示列标题的小部件,通常是一个文本小部件。
  • tooltip (String?): 当用户长按列标题时显示的提示信息。
  • numeric (bool): 指定该列是否为数字列,默认为 false。
  • onSort (Function(int columnIndex, bool ascending)?): 排序回调函数,当用户点击列标题时调用,用于处理数据的排序逻辑。
  • mouseCursor (MouseCursor?): 鼠标悬停在列标题上时显示的光标样式。
示例
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _sortAscending = true;
  int? _sortColumnIndex;

  List<User> _users = [
    User('Alice', 25),
    User('Bob', 30),
    User('Charlie', 35),
  ];

  void _sort<T>(Comparable<T> Function(User user) getField, int columnIndex, bool ascending) {
    _users.sort((a, b) {
      if (!ascending) {
        final User c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('DataTable Example'),
        ),
        body: SingleChildScrollView(
          child: DataTable(
            sortColumnIndex: _sortColumnIndex,
            sortAscending: _sortAscending,
            columns: [
              DataColumn(
                label: Text('Name'),
                tooltip: 'User\'s name',
                onSort: (int columnIndex, bool ascending) => _sort<String>((User user) => user.name, columnIndex, ascending),
              ),
              DataColumn(
                label: Text('Age'),
                numeric: true,
                tooltip: 'User\'s age',
                onSort: (int columnIndex, bool ascending) => _sort<num>((User user) => user.age, columnIndex, ascending),
              ),
            ],
            rows: _users.map((User user) {
              return DataRow(cells: [
                DataCell(Text(user.name)),
                DataCell(Text('${user.age}')),
              ]);
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class User {
  User(this.name, this.age);

  final String name;
  final int age;
}

DataRow

DataRow 是 Flutter 中用于定义 DataTable 表格中的一行。它包含了行的单元格、选择状态、长按事件等功能。

属性解析
const DataRow({
    this.key,
    this.selected = false,
    this.onSelectChanged,
    this.onLongPress,
    this.color,
    this.mouseCursor,
    required this.cells,
  })
  • key (LocalKey?): 唯一标识符,用于在树中标识该行。
  • selected (bool): 指定该行是否被选中,默认为 false。
  • onSelectChanged (ValueChanged<bool?>?): 当用户点击行的复选框时调用的回调函数。
  • onLongPress (GestureLongPressCallback?): 当用户长按行时调用的回调函数。
  • color (MaterialStateProperty<Color?>?): 行的背景颜色。
  • mouseCursor (MouseCursor?): 鼠标悬停在行上时显示的光标样式。
  • cells (List): 行中的单元格列表,每个单元格由 DataCell 定义。
示例
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _sortAscending = true;
  int? _sortColumnIndex;

  List<User> _users = [
    User('Alice', 25),
    User('Bob', 30),
    User('Charlie', 35),
  ];

  void _sort<T>(Comparable<T> Function(User user) getField, int columnIndex, bool ascending) {
    _users.sort((a, b) {
      if (!ascending) {
        final User c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('DataTable Example'),
        ),
        body: SingleChildScrollView(
          child: DataTable(
            sortColumnIndex: _sortColumnIndex,
            sortAscending: _sortAscending,
            columns: [
              DataColumn(
                label: Text('Name'),
                tooltip: 'User\'s name',
                onSort: (int columnIndex, bool ascending) => _sort<String>((User user) => user.name, columnIndex, ascending),
              ),
              DataColumn(
                label: Text('Age'),
                numeric: true,
                tooltip: 'User\'s age',
                onSort: (int columnIndex, bool ascending) => _sort<num>((User user) => user.age, columnIndex, ascending),
              ),
            ],
            rows: _users.map((User user) {
              return DataRow(
                selected: user.selected,
                onSelectChanged: (bool? value) {
                  setState(() {
                    user.selected = value ?? false;
                  });
                },
                cells: [
                  DataCell(Text(user.name)),
                  DataCell(Text('${user.age}')),
                ],
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class User {
  User(this.name, this.age, {this.selected = false});

  final String name;
  final int age;
  bool selected;
}

DataCell

DataCell 是 Flutter 中用于定义 DataRow 中单元格的小部件。它包含了单元格的显示内容、占位符状态、编辑图标以及各种手势事件。

属性解析
const DataCell(
    this.child, {
    this.placeholder = false,
    this.showEditIcon = false,
    this.onTap,
    this.onLongPress,
    this.onTapDown,
    this.onDoubleTap,
    this.onTapCancel,
  })
  • child (Widget): 单元格中显示的小部件,通常是一个文本小部件。
  • placeholder (bool): 指定该单元格是否为占位符,默认为 false。
  • showEditIcon (bool): 是否显示编辑图标,默认为 false。
  • onTap (GestureTapCallback?): 当用户点击单元格时调用的回调函数。
  • onLongPress (GestureLongPressCallback?): 当用户长按单元格时调用的回调函数。
  • onTapDown (GestureTapDownCallback?): 当用户按下单元格时调用的回调函数。
  • onDoubleTap (GestureDoubleTapCallback?): 当用户双击单元格时调用的回调函数。
  • onTapCancel (GestureTapCancelCallback?): 当单元格点击操作被取消时调用的回调函数。

 
 

Card

Card 是 Flutter 中用于创建卡片样式小部件的容器,它通常用于在应用中展示信息块。

属性解析

  const Card({
    super.key,
    this.color,
    this.shadowColor,
    this.surfaceTintColor,
    this.elevation,
    this.shape,
    this.borderOnForeground = true,
    this.margin,
    this.clipBehavior,
    this.child,
    this.semanticContainer = true,
  })
  • color (Color?): 卡片的背景颜色。
  • shadowColor (Color?): 卡片阴影的颜色。
  • surfaceTintColor (Color?): 卡片表面色调颜色。
  • elevation (double?): 卡片的阴影高度。
  • shape (ShapeBorder?): 卡片的形状及边框样式。
  • borderOnForeground (bool): 控制边框是在前景绘制还是背景绘制,默认值为 true。
  • margin (EdgeInsetsGeometry?): 卡片外边距,默认为 EdgeInsets.all(4.0)。
  • clipBehavior (Clip?): 设置裁剪行为。
  • child (Widget?): 卡片的子小部件。
  • semanticContainer (bool): 是否将卡片作为语义容器,默认为 true。

示例

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Card Example'),
        ),
        body: Center(
          child: Card(
            color: Colors.white,
            shadowColor: Colors.grey,
            elevation: 8.0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15.0),
            ),
            margin: EdgeInsets.all(16.0),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ListTile(
                    leading: Icon(Icons.album, size: 50),
                    title: Text('Card Title', style: TextStyle(fontSize: 24)),
                    subtitle:
                        Text('Card Subtitle', style: TextStyle(fontSize: 16)),
                  ),
                  ButtonBar(
                    children: <Widget>[
                      TextButton(
                        child: Text('ACTION 1'),
                        onPressed: () {
                          // Handle the action here
                        },
                      ),
                      TextButton(
                        child: Text('ACTION 2'),
                        onPressed: () {
                          // Handle the action here
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

在这里插入图片描述
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值