SliverPersistentHeader组件 实现Flutter吸顶效果

效果:

20230723-212152-73_Trim

代码:

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

class StickHeaderPage extends StatefulWidget {

  
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _StickHeaderPageState();
  }

}

class _StickHeaderPageState extends State<StickHeaderPage> {

  
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: const Text("Sticky Header"),
      ),
      body: CustomScrollView(
        slivers: [
          _topWidget(),
          _stickyHeader(),
          _listView(),
        ],
        physics: const BouncingScrollPhysics(),
      ),
    );
  }

  Widget _topWidget() {
    return SliverToBoxAdapter(
      child: Container(
        child: Image.network("https://2sc2.autoimg.cn/escimg/g27/M04/5D/0B/f_900x675_0_q87_autohomecar__ChxkmWMVdMCAJZdZAAFU8OPC7Xs588.jpg",
        ),
      ),
    );
  }

  Widget _stickyHeader() {
    return SliverPersistentHeader(
      pinned: true,
      floating: true,
      delegate: _StickyHeaderDelegate(
        minHeight: 50,
        maxHeight: 50,
        child: Container(
          height: 100,
          color: Colors.blue,
          alignment: Alignment.centerLeft,
          child: const Text("Sticky Header", style: TextStyle(fontSize: 20),),
        ),
      ),
    );
  }

  Widget _listView() {
    return SliverList(
      delegate:
        SliverChildBuilderDelegate( (context, index) {
          return Container(
              height: 50,
              color: index % 2 == 0 ? Colors.white : Colors.black12,
              width: double.infinity,
              alignment: Alignment.center,
              child: Text("Item $index"),
            );
        },
        childCount: 50,
      )
    );
  }

}

class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {

  _StickyHeaderDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    // TODO: implement build
    return SizedBox.expand(child: child,);
  }

  
  // TODO: implement maxExtent
  double get maxExtent => maxHeight;

  
  // TODO: implement minExtent
  double get minExtent => minHeight;

  
  bool shouldRebuild(covariant _StickyHeaderDelegate oldDelegate) {
    // TODO: implement shouldRebuild
    return (
        maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child
    );
  }


本文参考自:https://www.jianshu.com/p/b5292ef7c38c

你可能感兴趣的:(Flutter,flutter)