/*
 * @Author: XianKaiQun
 * @Date: 2020-04-21 08:47:59
 * @LastEditors: XianKaiQun
 * @LastEditTime: 2020-04-22 15:30:50
 * @Descripttion: 
 */
import 'package:flutter/widgets.dart';

///套在sliver中的列表构建
///
///简化 [SliverList] 和 [ExtSliverFixedExtentList] 的使用
///
///
class WisSliverList extends StatelessWidget {
  WisSliverList(
    this.delegate, {
    Key? key,
    this.padding,
    this.itemExtent,
    this.interval,
  }) : super(key: key);

  final SliverChildDelegate delegate;

  ///[padding]  不为null时，会套一个SliverPadding
  final EdgeInsetsGeometry? padding;

  ///[interval] 列表项间隔
  final double? interval;

  ///[itemExtent] 不为null且不为0时，列表项固定高度，固定高度性能更优，这是[SliverList]和[ExtSliverFixedExtentList]的差异
  final double? itemExtent;

  ///
  ///其他请参考[SliverChildBuilderDelegate]
  ///
  WisSliverList.childBuilder({
    this.padding,
    this.itemExtent,
    this.interval,
    required int childCount,
    required Widget Function(BuildContext, int) builder,
    int Function(Key)? findChildIndexCallback,
    bool addAutomaticKeepAlives = true,
    bool addRepaintBoundaries = true,
    bool addSemanticIndexes = true,
    int Function(Widget, int) semanticIndexCallback =
        _kDefaultSemanticIndexCallback,
    int semanticIndexOffset = 10,
  })  : 
        this.delegate = SliverChildBuilderDelegate(
          (_, i) {
            if ((interval ?? 0.0) == 0.0 || i + 1 == childCount) {
              return builder(_, i);
            } else {
              return Padding(
                padding: EdgeInsets.only(bottom: interval!),
                child: builder(_, i),
              );
            }
          },
          childCount: childCount,
          findChildIndexCallback: findChildIndexCallback,
          addAutomaticKeepAlives: addAutomaticKeepAlives,
          addRepaintBoundaries: addRepaintBoundaries,
          addSemanticIndexes: addSemanticIndexes,
          semanticIndexCallback: semanticIndexCallback,
          semanticIndexOffset: semanticIndexOffset,
        );
  @override
  Widget build(BuildContext context) {
    Widget current;
    if ((itemExtent ?? 0.0) == 0.0) {
      current = SliverList(delegate: delegate);
    } else {
      current = SliverFixedExtentList(
        delegate: delegate,
        itemExtent: itemExtent! + (interval ?? 0),
      );
    }
    if ((padding ?? EdgeInsets.zero) != EdgeInsets.zero) {
      current = SliverPadding(
        padding: padding!,
        sliver: current,
      );
    }
    return current;
  }
}

int _kDefaultSemanticIndexCallback(Widget _, int localIndex) => localIndex;
