/// 自定义粘性委托类
library;

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

typedef OnPinnedChanged = void Function(bool pinned);

class CustomStickyHeader extends SliverPersistentHeaderDelegate {
  final PreferredSize child;
  RxBool? isPinned;
  RxDouble? positions;

  CustomStickyHeader({
    required this.child,
    this.isPinned,
    this.positions,
  });

  @override
  double get minExtent => child.preferredSize.height;

  @override
  double get maxExtent => child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    // overlapsContent 或 shrinkOffset >= maxExtent - minExtent 都可以判断是否吸顶
    bool pinned = overlapsContent; // true 表示已经吸顶
    if (isPinned != null && isPinned!.value != pinned) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        isPinned!.value = pinned;
      });
    }
    if (positions != null) {
      if ((maxExtent - minExtent) >= shrinkOffset) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          positions!.value = shrinkOffset;
        });
      }
    }

    return child;
  }
}
