簡體   English   中英

Flutter - 顯示在 gridview 中滾動了多少項目

[英]Flutter - show how many items scrolled in gridview

我正在嘗試像下圖一樣實現。

在此處輸入圖像描述

我有一個網格視圖,其中有 2 列,我在其中顯示我的列表。

在此處輸入圖像描述

正如您在上圖中看到的那樣,它顯示了 175/67 種產品。

我的邏輯是我給我的網格視圖滾動 controller。

我正在為 controller 添加一個監聽器,但我認為我的邏輯或計算是錯誤的。

下面是我的代碼:

ScrollController _scrollController = new ScrollController();

在 initstate 我正在添加一個監聽器來滾動 controller

_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。

當我向下滾動時,它給出了錯誤的 output。

請告訴我哪里出錯了。

我的邏輯哪里出了問題?

下面是我的網格視圖代碼:

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'),
          ),
        ),
      ),
    );
  }
}

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

 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;
                                },
GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (_, index) => FlutterLogo(),
  itemCount: 4,)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM