首页 > 解决方案 > 如何在不使用构建器的情况下自动滚动页面视图并产生一些延迟?

问题描述

我制作了一个充当图像轮播的 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
                                )
                            )
                        )
                    }
                )

标签: flutterdart

解决方案


您需要在PageController您的PageView. 然后initState()你可以开始一个Timer.periodic()你只是从一个页面跳到另一个页面的地方。像这样:

注意:您必须在处理页面或其他事件时取消计时器。

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

@override
void initState() {
  super.initState();
  _timer = 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
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

@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.


推荐阅读