如何在不使用构建器的情况下自动滚动带有一些延迟的 PageView?

Zor*_*shi 9 dart flutter

我制作了一个用作图像轮播的 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
                                )
                            )
                        )
                    }
                )
Run Code Online (Sandbox Code Playgroud)

Gab*_*ndX 21

你需要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,
          ),
        ),
      ),
    ],
  );
}
Run Code Online (Sandbox Code Playgroud)

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