展开图块时如何滚动ExpansionTile / Listview? [英] How to scroll an ExpansionTile / Listview when a tile is expanded?

查看:70
本文介绍了展开图块时如何滚动ExpansionTile / Listview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ListView 中,我们有一堆 ExpansionTile (到目前为止还不是太疯狂了吧?)。我们的用户希望我们在打开 ExpansionTile 时自动滚动列表,因此新的扩展磁贴现在位于顶部(或尽可能顶部)。屏幕上的内容,因此他们不必手动滚动即可看到我们刚刚打开的内容。

We have a bunch of ExpansionTile within a ListView (so far not too crazy, right?). Our users would like us to "auto scroll" the list when they open up an ExpansionTile so the new expanded tile is now at the top (or as top as it can be) of the screen so they don't have to manually scroll to see what we just opened.

我认为我们需要在 ListView ScrollController 之类的东西c>-并注册一个onExpansionChanged ..做.. 某事。这对我来说还不算什么。 :)

I think we need something like a ScrollController on the ListView -- and to register an onExpansionChanged .. to do .. something. It's the something that's more than a bit vague to me. :)

任何指针或帮助您做到这一点的人,将不胜感激!

Any pointers or help on how to do this would be greatly appreciated!

TIA! p>

TIA!

推荐答案

如果我没弄错您的要求,基本上是一种自动滚动 ExpansionTile 向上,这样用户不必手动查看它的内容,对吧?

If I got right what your asking for, is basically a way to scroll automatically your ExpansionTile up so the user doesn't have to do it manually to see its content, right?

然后,您实际上可以使用 ListView 中> ScrollController 并利用<$ c的 onExpansionChanged 回调$ c> ExpansionTile 可以根据图块的大小(相对于当前位置)向上/向下滚动。

Then, you can actually use a ScrollController in your ListView and take advantage of the onExpansionChanged callback of the ExpansionTile to scroll it up/down accordingly to the size of the tile vs. its current position.

但是现在您想知道: 我怎么知道要滚动多少?

But now you are wondering: how do I know how much to scroll?

为此,您以前已经知道通过给它一些约束(例如,构建 Container(heigh:100.0))来构造窗口小部件的高度,或者在这种情况下,您不知道确切的高度 ExpansionTile 高度需要很多像素。因此,我们可以使用 GlobalKey ,然后通过在运行时检查其 RenderBox 来检查其渲染高度,以了解准确:折叠时需要多少像素并将其乘以其索引。

For that, either you know previously how exactly is the height of your widget when constructing it by giving it some constraints (like building a Container(heigh: 100.0)) or, in this particular scenario, you don't know exactly how many pixels the ExpansionTile height will take. So, we can use a GlobalKey and then check its rendering height by checking its RenderBox at runtime to know exactly how many pixels it's taking when collapsed and multiply it by its index.

  ExpansionTile _buildExpansionTile(int index) {
    final GlobalKey expansionTileKey = GlobalKey();
    double previousOffset;

    return ExpansionTile(
      key: expansionTileKey,
      onExpansionChanged: (isExpanded) {
        if (isExpanded) previousOffset = _scrollController.offset;
        _scrollToSelectedContent(isExpanded, previousOffset, index, expansionTileKey);
      },
      title: Text('My expansion tile $index'),
      children: _buildExpansionTileChildren(),
    );
  }

好,现在我们有了 ListView ,它将在生成器中使用此 _buildExpansionTile GlobalKey 。展开图块时,我们还保存了 ListView 的滚动偏移量。但是,实际上我们如何向上滚动以显示其内容?让我们看看 _scrollToSelectedContent 方法。

Ok, now we have a ListView that will use this _buildExpansionTile in its generator with a GlobalKey. We are also saving the scroll offset of the ListView when we expand the tile. But, how do we actually scroll up to show its content? Let's see the _scrollToSelectedContent method.

  void _scrollToSelectedContent(bool isExpanded, double previousOffset, int index, GlobalKey myKey) {
    final keyContext = myKey.currentContext;

    if (keyContext != null) {
      // make sure that your widget is visible
      final box = keyContext.findRenderObject() as RenderBox;
      _scrollController.animateTo(isExpanded ? (box.size.height * index) : previousOffset,
          duration: Duration(milliseconds: 500), curve: Curves.linear);
    }
  }

因此,我们通过其键访问渲染对象然后使用 ListView 滚动控制器在展开时向上滚动,并在折叠时通过将高度乘以其索引向下滚动回到其初始位置。您不必向后滚动,这只是我个人对本示例的偏爱。这将导致如下情况:

So, we are accessing the render object by its key and then use the ListView scroll controller to scroll up when expanded and down back to its initial position when collapsed by multiplying its height with its index. You don't have to scroll back, it was just my personal preference for this example. This will result in something like this:

在这里,您有 StatefulWidget

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyApp()));

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

class _MyAppState extends State<MyApp> {
  final ScrollController _scrollController = ScrollController();

  void _scrollToSelectedContent(bool isExpanded, double previousOffset, int index, GlobalKey myKey) {
    final keyContext = myKey.currentContext;

    if (keyContext != null) {
      // make sure that your widget is visible
      final box = keyContext.findRenderObject() as RenderBox;
      _scrollController.animateTo(isExpanded ? (box.size.height * index) : previousOffset,
          duration: Duration(milliseconds: 500), curve: Curves.linear);
    }
  }

  List<Widget> _buildExpansionTileChildren() => [
        FlutterLogo(
          size: 50.0,
        ),
        Text(
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vulputate arcu interdum lacus pulvinar aliquam. Donec ut nunc eleifend, volutpat tellus vel, volutpat libero. Vestibulum et eros lorem. Nam ut lacus sagittis, varius risus faucibus, lobortis arcu. Nullam tempor vehicula nibh et ornare. Etiam interdum tellus ut metus faucibus semper. Aliquam quis ullamcorper urna, non semper purus. Mauris luctus quam enim, ut ornare magna vestibulum vel. Donec consectetur, quam a mattis tincidunt, augue nisi bibendum est, quis viverra risus odio ac ligula. Nullam vitae urna malesuada magna imperdiet faucibus non et nunc. Integer magna nisi, dictum a tempus in, bibendum quis nisi. Aliquam imperdiet metus id metus rutrum scelerisque. Morbi at nisi nec risus accumsan tempus. Curabitur non sem sit amet tellus eleifend tincidunt. Pellentesque sed lacus orci.',
          textAlign: TextAlign.justify,
        ),
      ];

  ExpansionTile _buildExpansionTile(int index) {
    final GlobalKey expansionTileKey = GlobalKey();
    double previousOffset;

    return ExpansionTile(
      key: expansionTileKey,
      onExpansionChanged: (isExpanded) {
        if (isExpanded) previousOffset = _scrollController.offset;
        _scrollToSelectedContent(isExpanded, previousOffset, index, expansionTileKey);
      },
      title: Text('My expansion tile $index'),
      children: _buildExpansionTileChildren(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MyScrollView'),
      ),
      body: ListView.builder(
        controller: _scrollController,
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) => _buildExpansionTile(index),
      ),
    );
  }
}

这篇关于展开图块时如何滚动ExpansionTile / Listview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆