Flutter ListView获取页面显示的第一个和最后一个item、点击item自动偏移居中ListView

本文介绍了如何在Flutter中实现ListView的两个高级特性:监听显示的第一个和最后一个item,以及点击item自动居中。通过自定义SliverChildBuilderDelegate和ScrollController,实现了列表边界检测和动态滚动效果。同时提供了简洁的代码示例,适用于需要此类功能的开发者。

本文章是两个flutter小组件listview的两个功能,这里做一个分享方便以后其他衍生特殊高级功能的开发,扩宽你的思路:

一、ListView获取页面显示的第一个和最后一个item

1.listview 中利用custom才能监听到第一个条目
new ListView.custom(
  controller: controller,
  cacheExtent: 1.0, // 只有设置了1.0 才能够准确的标记position 位置
  childrenDelegate:  MyChildrenDelegate(
        (BuildContext context, int index) {
//Dismissible这个可以用作列表的横向滑动删除功能效果
      return new Dismissible(
          key: new Key(list[index]),
          onDismissed: (direction) {
            //被移除回掉
            list.removeAt(index);
            var item = list[index];
            Scaffold.of(context).showSnackBar(
                new SnackBar(content: new Text("$item")));
          },
          child: new ListTile(
            title: new Text(list[index]),
          ));
    },
    childCount: list.length,
  ),
)

SliverChildBuilderDelegate 

class _SaltedValueKey extends ValueKey{
  const _SaltedValueKey(Key key): assert(key != null), super(key);
}
class MyChildrenDelegate extends SliverChildBuilderDelegate {
  MyChildrenDelegate(
      Widget Function(BuildContext, int) builder, {
        int childCount,
        bool addAutomaticKeepAlive = true,
        bool addRepaintBoundaries = true,
      }) : super(builder,
      childCount: childCount,
      addAutomaticKeepAlives: addAutomaticKeepAlive,
      addRepaintBoundaries: addRepaintBoundaries);
  // Return a Widget for the given Exception
  Widget _createErrorWid
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值