如何更改固定的Sliver Persistent Header

时间:2019-08-01 15:13:03

标签: flutter

我正在GridView上方使用2个Sliver标头,并在CustomScrollView上使用ListView。当向下滚动时,我只希望固定其中一个标题(正在滚动的标题)。我希望能够向下滚动,并且在通过Gridview时仅固定了其中一个标题。

编辑: 添加了_SliverAppBarDelegate

Scaffold(
body: SafeArea(
        child: DefaultTabController(
          length: 2,
          child: CustomScrollView(
            slivers: [              
              makeHeader('Categories', false),
              SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 1.5,
                ),
                delegate: SliverChildBuilderDelegate(
                    (context, index) => Container(
                          margin: EdgeInsets.all(5.0),
                          color: Colors.blue,
                        ),
                    childCount: 10),
              ),
              makeHeader('Watchlist', false),
              SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 1.5,
                ),
                delegate: SliverChildBuilderDelegate(
                    (context, index) => Container(
                          margin: EdgeInsets.all(5.0),
                          color: Colors.red,
                        ),
                    childCount: 10),
              ),
            ],
          ),
        ),
  ),
)


SliverPersistentHeader makeHeader(String headerText, bool pinned) {
  return SliverPersistentHeader(
    pinned: pinned,
     floating: true,
    delegate: _SliverAppBarDelegate(
      minHeight: 40.0,
      maxHeight: 60.0,
      child: Container(
          child: Text(
            headerText,
            style: TextStyle(fontSize: 24, color: Colors.green,fontWeight: FontWeight.bold),
          )),
    ),
  );
}

///////////////////////////EDIT

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    this.child,
  });
  final double minHeight;
  final double maxHeight;
  final Widget child;
  @override
  double get minExtent => minHeight;
  @override
  double get maxExtent => math.max(maxHeight, minHeight);
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}

1 个答案:

答案 0 :(得分:0)

@diegoveloper我找到了这个插件。 https://pub.dev/packages/flutter_sticky_header 我希望没有插件也可以有一种更简单的方法。但是,此插件恰好解决了我正在描述的问题。