Flutter - 显示在 gridview 中滚动了多少项目

Flutter - show how many items scrolled in gridview

我正在尝试像下图那样实现。

我有一个网格视图,其中有 2 列,我在其中显示我的列表。

正如您在上图中看到的,它显示了 175/67 种产品。

我的逻辑是我正在给我的网格视图一个滚动控制器。

我正在为那个控制器添加一个监听器,但我认为我的逻辑或计算是错误的。

下面是我的代码:

ScrollController _scrollController = new ScrollController();

在 initstate 中,我正在给滚动控制器添加一个监听器

_scrollController.addListener(_scrollListener);

void _scrollListener() {
    setState(() {
      debugPrint(_scrollController.offset.toString());
      debugPrint(count.toString());
      debugPrint(((_scrollController.offset / count).round()).toString());
      index = (_scrollController.offset / count).round();
      print(index);
    });
  }

计数是我列表中的项目总数,即 67。

当我向下滚动时,它给出了错误的输出。

请告诉我哪里错了。

我的逻辑哪里出了问题?

下面是我的网格视图代码:

DragSelectGridView(
                      shrinkWrap: true,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        childAspectRatio: (itemWidth / itemHeight),
                        crossAxisCount: 2,
                      ),
                      physics: ClampingScrollPhysics(),
                      gridController: gridController,
                      scrollController: _scrollController,
                      itemCount: items.length,
                      itemBuilder: (context, index, selected) {
                       
                        return ProductCard(
                          data: items[index],
                          isSelected: selected,
                        );
                      },
                    ),

提前致谢!!!

您可以使用ScrollablePositionedList 获取当前可见项的索引。在这里查看我的示例应用程序:

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

const numberOfItems = 500;
const randomMax = 1 << 32;

void main() {
  runApp(ScrollablePositionedListExample());
}

class ScrollablePositionedListExample extends StatelessWidget {
  const ScrollablePositionedListExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example App',
      home: const SampleApp(),
    );
  }
}

class SampleApp extends StatefulWidget {
  const SampleApp({Key? key}) : super(key: key);

  @override
  _SampleAppState createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();
  late List<Color> itemColors;

  @override
  void initState() {
    super.initState();
    final colorGenerator = Random(42490823);
    itemColors = List<Color>.generate(numberOfItems,
        (int _) => Color(colorGenerator.nextInt(randomMax)).withOpacity(1));
  }

  @override
  Widget build(BuildContext context) => Material(
        child: OrientationBuilder(
          builder: (context, orientation) => Column(
            children: <Widget>[
              Expanded(
                child: ScrollablePositionedList.builder(
                  itemCount: numberOfItems,
                  itemBuilder: (context, index) => item(
                    index,
                  ),
                  itemScrollController: itemScrollController,
                  itemPositionsListener: itemPositionsListener,
                  scrollDirection: Axis.vertical,
                ),
              ),
              positionsView,
            ],
          ),
        ),
      );

  Widget get positionsView => ValueListenableBuilder<Iterable<ItemPosition>>(
        valueListenable: itemPositionsListener.itemPositions,
        builder: (context, positions, child) {
          int? currentPosition;
          if (positions.isNotEmpty) {
            currentPosition = positions
                .where((ItemPosition position) => position.itemLeadingEdge < 1)
                .reduce((ItemPosition max, ItemPosition position) =>
                    position.itemLeadingEdge > max.itemLeadingEdge
                        ? position
                        : max)
                .index;
          }
          return Container(
              color: Colors.grey,
              padding: EdgeInsets.all(10),
              child: Text('${currentPosition ?? ''}/$numberOfItems}'));
        },
      );

  Widget item(int i) {
    return InkWell(
      // You can still click on the item here, for example put it in to the cart, etc
      onTap: () => Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => Scaffold(
                appBar: AppBar(),
              ))),
      child: SizedBox(
        height: 150,
        child: Container(
          color: itemColors[i],
          child: Center(
            child: Text('Item $i'),
          ),
        ),
      ),
    );
  }
}
GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (_, index) => FlutterLogo(),
  itemCount: 4,)

查看此代码,看看它是否有用

 NotificationListener<ScrollNotification>(
                                onNotification: (notification) {
                                  //get height of each item
                                  var height=notification.metrics.maxScrollExtent/items.length;
                                  //get position of item
                                  var position=((notification.metrics.maxScrollExtent-notification.metrics.extentAfter)/height).round();
                                  print('postion is $position and the lenght is ${_catcontroller.products.length}');
                                  return true;
                                },