我制作了一个PageView,用作图像轮播。
在Flutter延迟一段时间后,如何让它自动在其页面之间无限滚动?

                new PageView(
                    children: List<Widget> {
                        new Container(
                            decoration: BoxDecoration(
                                image: DecorationImage(image: new AssetImage(images[0]),
                                fit: BoxFit.cover
                                )
                            )
                        ),
                        new Container(
                            decoration: BoxDecoration(
                                image: DecorationImage(image: new AssetImage(images[1]),
                                fit: BoxFit.cover
                                )
                            )
                        ),
                        new Container(
                            decoration: BoxDecoration(
                                image: DecorationImage(image: new AssetImage(images[2]),
                                fit: BoxFit.cover
                                )
                            )
                        )
                    }
                )

最佳答案

您需要在PageController中添加PageView。然后,在initState()上,您可以启动Timer.periodic(),在这里您可以从一个页面跳转到另一个页面。像这样:

int _currentPage = 0;
PageController _pageController = PageController(
  initialPage: 0,
);

@override
void initState() {
  super.initState();
  Timer.periodic(Duration(seconds: 5), (Timer timer) {
    if (_currentPage < 2) {
      _currentPage++;
    } else {
      _currentPage = 0;
    }

    _pageController.animateToPage(
      _currentPage,
      duration: Duration(milliseconds: 350),
      curve: Curves.easeIn,
    );
  });
}

@override
Widget build(BuildContext context) {
  return PageView(
    controller: _pageController,
    children: [
      Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: new AssetImage(images[0]),
            fit: BoxFit.cover,
          ),
        ),
      ),
      Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: new AssetImage(images[1]),
            fit: BoxFit.cover,
          ),
        ),
      ),
      Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: new AssetImage(images[2]),
            fit: BoxFit.cover,
          ),
        ),
      ),
    ],
  );
}

顺便说一句,您需要导入'dart:async'以使用Timer

关于flutter - 如何在不使用生成器的情况下延迟某些时间自动滚动PageView?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56780188/

10-12 06:08