-1

我正在尝试实现如下图所示。

在此处输入图像描述

我有一个网格视图,它有 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,
                        );
                      },
                    ),

提前致谢!!!

4

4 回答 4

0

看看这段代码,看看它有用与否

 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;
                                },
于 2021-10-12T09:40:10.777 回答
0

您可以使用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'),
          ),
        ),
      ),
    );
  }
}
于 2021-10-12T09:23:53.587 回答
-1
GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (_, index) => FlutterLogo(),
  itemCount: 4,)
于 2021-10-12T09:38:31.707 回答
-1

我认为最好使用scrollable_positioned_list 并使用当前项目的索引而不是项目偏移量

于 2021-10-12T09:00:32.227 回答