flutter - Flutter:如何平滑 PageView onPageChanged 动画
问题描述
如果您按照网上找到的示例代码,在构建脚手架时,在 body 下,您可以:
body: PageView(
controller: _pageController,
onPageChanged: (index) {
setState(() => _selectedPage = index);
},
children: <Widget>[
Container(color: Colors.pink,),
Container(color: Colors.cyan,),
Container(color: Colors.deepPurple,),
],
)
当您在显示粉红色的页面上并向左滑动时,会从右侧出现一页青色。但是,现在我为我的用例扩展了它,现在有:
body: PageView(
controller: _pageController,
onPageChanged: (index) {
setState(() => _selectedPage = index);
},
children: <Widget>[
Container(child: _pageOptions[_selectedPage],),
Container(child: _pageOptions[_selectedPage],),
Container(child: _pageOptions[_selectedPage],),
],
)
“_pageOptions[]”定义如下:
final _pageOptions = [
Page1(),
Page2(),
Page3(),
];
我的问题如下:例如,当您在 Page1 上并向左滑动时, Page2 应该来自右侧并成为您正在查看的新页面。但是,当您从 Page1 慢慢滑动到 Page2 时,您可以看到从右边来的页面是 Page1 而不是 Page2。直到您轻扫一半,传入页面变为 Page2。但是,此时,您正在向左侧滑动的页面(应该是 Page1)也变为 Page2。
我怎样才能解决这个问题?Page1() 和其余的返回一个小部件。例如,Page1 类编码为:
class Page1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(25.0),
child: Text('Page1', style: TextStyle(fontSize: 36.0),)
);
}
}
解决方案
在:
children: <Widget>[
Container(child: _pageOptions[_selectedPage],),
Container(child: _pageOptions[_selectedPage],),
Container(child: _pageOptions[_selectedPage],),
],
孩子们的变化取决于 _selectedPage,它在 onPageChanged 时发生变化。
如果您在 Page1 中,_selectedPage = 1,因此所有子项都是 Page1 的 _pageOptions[1]。将代码更改为:
children: <Widget>[
Container(child: _pageOptions[0],),
Container(child: _pageOptions[1],),
Container(child: _pageOptions[2],),
],
推荐阅读
- google-visualization - response.isError 为真,因为“请求超时”
- html - 打印时在 HTML 表中添加奇数行
- spring-boot - 具有 JWT 授权和 Angular 6 登录的 Spring Security
- python - 在 Gurobi /python 界面中修复的代码问题
- javascript - 反应刷新页面
- typescript - 如何使用打字稿将我的数组动态加载到我的大型菜单的列中?
- html - col-8 bootstrap 内的行背景全宽
- android - Android minifyEnabled true 导致应用程序崩溃
- python - ImportError:无法从“gym.wrappers”导入名称“SkipWrapper”
- json - 如何写入 JSON 文件而不删除其中的所有内容?