如何在flutter中粘住表格的表头?

问题描述 投票:0回答:1

我想当用户向下滚动页面时粘住表格的标题,直到该标题消失,并在用户向下滚动页面直到该表格消失后停止粘住它。 我正在使用

Table
小部件。我尝试了 sticky_headers: ^0.3.0+2,但没有成功。

我们可以在不使用

scrollController
和表格包的情况下做到这一点吗(我必须使用
Table
小部件)?

示例代码:

Widget page() {
  return Scaffold(
    body: SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            otherWidget1(),
            tableWidget1(),
            otherWidget2(),
            tableWidget2(),
          ],
        ),
      ),
    ),
  );
}

Widget tableWidget(){
  return Table(
    children: [
      headerWidget, //I want to sticky it!
      bodyWidget,
    ],
  );
}
flutter
1个回答
0
投票

要在不使用滚动控制器或外部包的情况下为表格实现粘性标题,您可以使用 ListView 和 Table 小部件的组合。您可以通过以下方式修改代码来实现此目的:

import 'package:flutter/material.dart';

Widget page() {
  return Scaffold(
    body: SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            otherWidget1(),
            StickyTableWidget(
              header: headerWidget1(),
              body: bodyWidget1(),
            ),
            otherWidget2(),
            StickyTableWidget(
              header: headerWidget2(),
              body: bodyWidget2(),
            ),
          ],
        ),
      ),
    ),
  );
}

Widget otherWidget1() {
  // Widget for other content before table 1
}

Widget otherWidget2() {
  // Widget for other content before table 2
}

Widget headerWidget1() {
  // Widget for header of table 1
}

Widget bodyWidget1() {
  // Widget for body of table 1
}

Widget headerWidget2() {
  // Widget for header of table 2
}

Widget bodyWidget2() {
  // Widget for body of table 2
}

class StickyTableWidget extends StatelessWidget {
  final Widget header;
  final Widget body;

  const StickyTableWidget({
    Key? key,
    required this.header,
    required this.body,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        header,
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: ConstrainedBox(
            constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width),
            child: body,
          ),
        ),
      ],
    );
  }
}

在此代码中:

  1. StickyTableWidget 是一个自定义小部件,包含表格的标题和正文。当正文水平滚动时,标题保持粘性。
  2. 页面函数包含分别用于表 1 和表 2 的两个 StickyTableWidget 实例,每个实例都有自己的标题和正文小部件。
  3. 您需要使用自己的其他内容和表格组件的小部件来实现 otherWidget1、otherWidget2、headerWidget1、bodyWidget1、headerWidget2 和 bodyWidget2 函数。

这种方法应该提供您正在寻找的粘性标题行为,而不需要外部包或滚动控制器。

© www.soinside.com 2019 - 2024. All rights reserved.