简体   繁体   English

如何让 ListView 在滑动时滚动到下一个元素?

[英]How to make ListView scroll to the next element on swipe?

I'm trying to make ListView swipe work in a way similar to the scroll_navigation library.我正在尝试以类似于 scroll_navigation 库的方式使 ListView 滑动工作。 I want each swipe to scroll to the next 100%-wide element without stopping in any place between.我希望每次滑动都能滚动到下一个 100% 宽的元素,而不会停在两者之间的任何地方。 Is it possible or should I use another widget?有可能还是我应该使用另一个小部件?

class HorizontalScroll extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      scrollDirection: Axis.horizontal,
      children: <Widget>[
        Container(
          width: 400,
          color: Colors.purple[600],
          child: const Center(
              child: Text(
            'Item 1',
            style: TextStyle(fontSize: 18, color: Colors.white),
          )),
        ),
        Container(
          width: 400,
          color: Colors.purple[500],
          child: const Center(
              child: Text(
            'Item 2',
            style: TextStyle(fontSize: 18, color: Colors.white),
          )),
        ),
        Container(
          width: 400,
          color: Colors.purple[400],
          child: const Center(
              child: Text(
            'Item 3',
            style: TextStyle(fontSize: 18, color: Colors.white),
          )),
        ),
        Container(
          width: 400,
          color: Colors.purple[300],
          child: const Center(
              child: Text(
            'Item 4',
            style: TextStyle(fontSize: 18, color: Colors.white),
          )),
        ),
      ],
    );
  }
}

在此处输入图像描述

You can use PageView您可以使用PageView

PageView(
      children: [
        Center(child: Text('Page 1')),
        Center(child: Text('Page 2')),
        Center(child: Text('Page 3')),
        Center(child: Text('Page 4')),
      ],
    )

To achieve this, the easiest method is to use a PageView instead of a ListView .为此,最简单的方法是使用PageView而不是ListView It will by default do what you want, scroll to the next 100% wide element.默认情况下,它会做你想做的事,滚动到下一个 100% 宽的元素。 Here is an example:这是一个例子:

PageView(
  children: <Widget>[
    Container(
      color: Colors.amber,
    ),
    Container(
      color: Colors.black,
    ),
    Container(
      color: Colors.white,
    ),
  ],
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM