【问题标题】:flutter - How to auto scroll to index with dynamic height programmatically颤振 - 如何以编程方式自动滚动到具有动态高度的索引
【发布时间】:2019-12-25 03:35:44
【问题描述】:

根据 Flutter 的 issue here ,目前不支持 Auto-Scroll to Index 每个单元格/项目具有动态高度。我尝试了另一种解决方案,但没有奏效。

那么,将ListViewAutoScroll 制作为动态高度的临时解决方案是什么?

有什么想法吗?

【问题讨论】:

  • 如果列表中的 每个 项具有完全随机的高度(动态),并且您想在呈现视图时滚动到项 N,您'必须在要跳转到的帖子框架中找到RenderObject 的高度/位置,然后自动滚动到那里应该没问题。
  • 如果你滚动到一个之前已经渲染过的项目,你能缓存它的位置并滚动到这个位置而不是它的索引吗?此外,对列表的任何更改都会使其后面的所有项目的位置无效。

标签: android flutter dart scroll flutter-layout


【解决方案1】:

你的问题

那么,使用 AutoScroll 制作 ListView 以获得动态高度的临时解决方案是什么?

屏幕录像

解决方案

滚动到索引包

此包为 Flutter 可滚动小部件提供固定/可变行高的滚动到索引机制。

这是一个小部件级别的库,意味着您可以在任何 Flutter 可滚动小部件中使用此机制。

用法

pubspec.yaml

 scroll_to_index: any

来自quire-io/scroll-to-index: scroll to index with fixed/variable row height inside Flutter scrollable widget的示例

使用 - 控制器

controller.scrollToIndex(index, preferPosition: AutoScrollPosition.begin)

用法 - 列表视图

ListView(
scrollDirection: scrollDirection,
controller: controller,
children: randomList.map<Widget>((data) {
    final index = data[0];
    final height = data[1];
    return AutoScrollTag(
    key: ValueKey(index),
    controller: controller,
    index: index,
    child: Text('index: $index, height: $height'),
    highlightColor: Colors.black.withOpacity(0.1),
    );
}).toList(),
)

询问了额外的 unixercoder

这是有限列表还是无限列表?

使用ListView.builder模拟无限列表

    ListView.builder(
    scrollDirection: scrollDirection,
    controller: controller,
    itemBuilder: (context, i) => Padding(
      padding: EdgeInsets.all(8),
      child: _getRow(i, (min + rnd.nextInt(max - min)).toDouble()),
    ),

它在 22 次尝试中获得了 18 次正确,大约 (81%) 或接近它

屏幕录像

所以它不支持 100%

参考:

第一屏录像代码

//Copyright (C) 2019 Potix Corporation. All Rights Reserved.
//History: Tue Apr 24 09:29 CST 2019
// Author: Jerry Chen

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

第二屏录像代码:

//Copyright (C) 2019 Potix Corporation. All Rights Reserved.
//History: Tue Apr 24 09:29 CST 2019
// Author: Jerry Chen

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> {
  final scrollDirection = Axis.vertical;
  var rnd = math.Random();
  int min = 50;
  int max = 200;
  AutoScrollController controller;
  @override
  void initState() {
    super.initState();
    controller = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: scrollDirection);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
        scrollDirection: scrollDirection,
        controller: controller,
        itemBuilder: (context, i) => Padding(
          padding: EdgeInsets.all(8),
          child: _getRow(i, (min + rnd.nextInt(max - min)).toDouble()),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToIndex,
        tooltip: 'Increment',
        child: Text(counter.toString()),
      ),
    );
  }

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

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

【讨论】:

  • 这是finiteinfinite 列表吗?
  • @anunixercoder ,有限但不是无限,查看答案了解更多详情
  • 嗨,我可以使用ListView.builder 来获取有限列表吗?
  • 这解决了具有不规则高度的列表,但它不能解决具有实际动态高度的列表(也就是高度随时间变化)。我有一个处理每一行数据的块。当它获取数据时,该行将相应地扩展。现在我不知道如何准确地滚动到某个索引。它总是关闭。
【解决方案2】:

这个包可能是您正在寻找的包。您可以为每个小部件分配 id 并启用动画,就像 HTML 中的标签一样。

https://pub.dev/packages/scroll_to_id

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  final ScrollToId scrollToId = ScrollToId();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll to ID',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Scroll to ID'),
        ),
        body: Stack(
          alignment: Alignment.topRight,
          children: [
            InteractiveScrollViewer(
              scrollToId: scrollToId,
              children: [
                ScrollContent(
                  id: '1',
                  child: Container(
                    height: 600,
                    color: Colors.green,
                  ),
                ),
                ScrollContent(
                  id: '2',
                  child: Container(
                    height: 800,
                    color: Colors.red,
                  ),
                ),
                ScrollContent(
                  id: '3',
                  child: Container(
                    height: 300,
                    color: Colors.yellow,
                  ),
                ),
                ScrollContent(
                  id: '4',
                  child: Container(
                    height: 700,
                    color: Colors.blue,
                  ),
                ),
              ],
            ),
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.white, width: 3),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  GestureDetector(
                    child: Container(
                      width: 100,
                      alignment: Alignment.center,
                      height: 50,
                      child: Text('1', style: TextStyle(color: Colors.white),),
                      color: Colors.green,
                    ),
                    onTap: () {
                      scrollToId.scroll(id: '1');
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      width: 100,
                      alignment: Alignment.center,
                      height: 50,
                      child: Text('2', style: TextStyle(color: Colors.white),),
                      color: Colors.red,
                    ),
                    onTap: () {
                      scrollToId.scroll(id: '2');
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      width: 100,
                      alignment: Alignment.center,
                      height: 50,
                      child: Text('3', style: TextStyle(color: Colors.white),),
                      color: Colors.yellow,
                    ),
                    onTap: () {
                      scrollToId.scroll(id: '3');
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      width: 100,
                      alignment: Alignment.center,
                      height: 50,
                      child: Text('4', style: TextStyle(color: Colors.white),),
                      color: Colors.blue,
                    ),
                    onTap: () {
                      scrollToId.scroll(id: '4');
                    },
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

【讨论】:

    【解决方案3】:

    如何观察当前的偏移索引?

        controller.addListener(() {
          AutoScrollTagState sts = controller.tagMap[0];
          print(sts);
        });
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2018-02-18
      相关资源
      最近更新 更多