flutter에서 scrollController의 스크롤링 인덱스를 표시하는 방법은 무엇입니까?

Aug 21 2020

다음 이미지에 표시된 것과 동일한 방식으로 scrollController를 사용하여 listView의 맨 아래에 인덱스를 표시하고 싶습니다.

사용자가 아래로 스크롤하거나 위로 스크롤하면 빨간색으로 강조 표시된 왼쪽의 카운트가 사용자의 스크롤 방향에 따라 증가 / 감소됩니다.

내가 원하는 것은 그림에서 빨간색으로 표시된 표시된 항목의 색인을 자동으로 업데이트하는 것입니다. 따라서 사용자가 아래 또는 위로 스크롤 할 때마다이 색인은 표시된 항목의 색인에 따라 업데이트됩니다.

사진은 제가 26 번째 항목에 도달했음을 보여줍니다. 아래 또는 위로 스크롤 할 때마다이 색인이 업데이트됩니다.

나는 운이없는 스크롤 이벤트에 대해 방출되는 오프셋을 사용해 보았습니다.

답변

2 Rod Aug 21 2020 at 02:23

방법은 당신이하던 것처럼 스크롤 컨트롤러를 사용하는 것입니다.

알려진 항목 크기와 리스너를 사용해야합니다.

// Declaring the controller and the item size
ScrollController _scrollController;
final itemSize = 100.0;

// Initializing
@override
void initState() {
  _scrollController = ScrollController();
  _scrollController.addListener(_scrollListener);
  super.initState();
}

// Your list widget (must not be nested lists)
ListView.builder(
      controller: _scrollController,
      itemCount: <Your list length>,
      itemExtent: itemSize,
      itemBuilder: (context, index) {
          return ListTile(<your items>);
      },
),

// With the listener and the itemSize, you can calculate which item
// is on screen using the provided callBack. Something like this:
void _scrollListener() {
  setState(() {
    var index = (_scrollController.offset / itemSize).round() + 1;
  });
}

scrollController에 리스너를 추가하면 목록이 스크롤 될 때마다 제공되는 콜백이 호출됩니다. 리스너를 실행 한 이벤트 유형, 스크롤 방향 등을 식별하는 것을 포함하여 동일한 논리를 사용하여 목록의 여러 동작을 처리 할 수 ​​있습니다.

LouisBelmont Aug 21 2020 at 01:52

당신을 도울 수있는 색인 스크롤 이라는 lib가 있습니다. $ index를 가져 와서 토스트 메시지 안에 표시 할 수 있습니다. 아래 예제는 lib 작성자의 것입니다.

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll To Index Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Scroll To Index Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  static const maxCount = 100;
  final random = math.Random();
  final scrollDirection = Axis.vertical;

  AutoScrollController controller;
  List<List<int>> randomList;

  @override
  void initState() {
    super.initState();
    controller = AutoScrollController(
      viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
      axis: scrollDirection
    );
    randomList = List.generate(maxCount, (index) => <int>[index, (1000 * random.nextDouble()).toInt()]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        scrollDirection: scrollDirection,
        controller: controller,
        children: randomList.map<Widget>((data) {
          return Padding(
            padding: EdgeInsets.all(8),
            child: _getRow(data[0], math.max(data[1].toDouble(), 50.0)),
          );
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToIndex,
        tooltip: 'Increment',
        child: Text(counter.toString()),
      ),
    );
  }

  int counter = -1;
  Future _scrollToIndex() async {
    setState(() {
      counter++;

      if (counter >= maxCount)
        counter = 0;
    });

    await controller.scrollToIndex(counter, preferPosition: AutoScrollPosition.begin);
    controller.highlight(counter);
  }

  Widget _getRow(int index, double height) {
    return _wrapScrollTag(
      index: index,
      child: Container(
        padding: EdgeInsets.all(8),
        alignment: Alignment.topCenter,
        height: height,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.lightBlue,
            width: 4
          ),
          borderRadius: BorderRadius.circular(12)
        ),
        child: Text('index: $index, height: $height'),
      )
    );
  }

  Widget _wrapScrollTag({int index, Widget child})
  => AutoScrollTag(
    key: ValueKey(index),
    controller: controller,
    index: index,
    child: child,
    highlightColor: Colors.black.withOpacity(0.1),
  );
}
AlperenEkin Aug 21 2020 at 13:18

https://medium.com/flutter-community/create-shop-list-with-flutter-d13d3c20d68b아마도 이것이 당신을 도울 수 있습니다. 또한 소스 코드를 사용할 수 있습니다. 항목 높이에 대한 간단한 수학이 도움이 될 수 있습니다.