【问题标题】:How to scroll to the index with SliverList?如何使用 SliverList 滚动到索引?
【发布时间】:2021-11-04 04:00:48
【问题描述】:

滚动到索引适用于 ListView 小部件,但不适用于 customScrollView 中的 SliverList。修改this“滚动到索引”示例,将 ListView 替换为 SliverList。此外,尝试了过去类似的问题,但没有任何运气。

想要的结果是通过点击按钮滚动到索引。

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 {
  @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, required 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;
 
  late AutoScrollController controller;
  late 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, (200 * random.nextDouble()).toInt()]);
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: ScrollController(),
        slivers: [
          SliverAppBar(
            pinned: true,
            title: Text("App bar"),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return Padding(
                  padding: EdgeInsets.all(8),
                  child: _getRow(
                    randomList[index][0],
                    math.max(randomList[index][1].toDouble(), 50.0),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      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({required int index, required Widget child}) =>
      AutoScrollTag(
        key: ValueKey(index),
        controller: controller,
        index: index,
        child: child,
        highlightColor: Colors.black.withOpacity(0.7),
      );
}

【问题讨论】:

    标签: flutter dart s


    【解决方案1】:

    您可以尝试使用 Scrollable.ensureVisible(您必须为每个列表项指定一个唯一键,然后使用它来确保该项可见)。

    【讨论】:

    • 是的,结果是它几乎可以工作。第一次滚动尝试后丢失密钥。到目前为止,有效的解决方案是 SliverToBoxAdapter、Column 和 ListView with Scrollable.ensureVisble
    猜你喜欢
    • 2021-07-21
    • 2020-03-16
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2019-05-20
    • 2020-12-18
    • 1970-01-01
    相关资源
    最近更新 更多