首页 > 解决方案 > 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),)
    );
    }
}

标签: flutterflutter-pageview

解决方案


在:

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],),
],

推荐阅读