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
)
)
)
}
)
解决方案
您需要在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
.
推荐阅读
- excel - 在一个单元格中匹配多个部分文本并在 excel 中返回最大日期
- editor - 如何在 pine 编辑器中的指定时间范围和图表会话中为我的条形高点创建水平线
- visual-studio - c#:如何强制类表示层调用 Dal 层?
- docker - 考虑 URL 重定向:如何在远程服务器上的同一 docker 网络中使用在不同容器中运行的 Web 应用程序的 GUI?
- list - Discord.py:如何使用 discord.Profile.connected_accounts
- javascript - 在javascript中的两个选择框之间交换所有值
- python - 在 Python 中运行的套接字服务器和网络服务器
- docker - 如何创建新的 docker 容器并从 Jenkinsfile 运行它
- arrays -
在另一个循环中循环一个 ngfor 循环 - mysql - MySQL大表性能优化