
微信交流群
# PageView
PageView 控件可以实现一个“图片轮播”的效果,PageView 不仅可以水平滑动也可以垂直滑动,简单用法如下:
PageView(
children: <Widget>[
MyPage1(),
MyPage2(),
MyPage3(),
],
)
1
2
3
4
5
6
7
2
3
4
5
6
7
PageView滚动方向默认是水平,可以设置其为垂直方向:
PageView(
scrollDirection: Axis.vertical,
...
)
1
2
3
4
2
3
4
PageView配合PageController可以实现非常酷炫的效果,控制每一个Page不占满,
PageView(
controller: PageController(
viewportFraction: 0.9,
),
...
)
1
2
3
4
5
6
2
3
4
5
6
PageController中属性initialPage
表示当前加载第几页,默认第一页。
onPageChanged
属性是页面发生变化时的回调,用法如下:
PageView(
onPageChanged: (int index){
},
...
)
1
2
3
4
5
2
3
4
5
# 无限滚动
PageView滚动到最后时希望滚动到第一个页面,这样看起来PageView是无限滚动的:
List<Widget> pageList = [PageView1(), PageView2(), PageView3()];
PageView.builder(
itemCount: 10000,
itemBuilder: (context, index) {
return pageList[index % (pageList.length)];
},
)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
巧妙的利用取余重复构建页面实现PageView无限滚动的效果:
# 实现指示器
指示器显示总数和当前位置,通过onPageChanged
确定当前页数并更新指示器。
List<String> pageList = ['PageView1', 'PageView2', 'PageView3'];
int _currentPageIndex = 0;
_buildPageView() {
return Center(
child: Container(
height: 230,
child: Stack(
children: <Widget>[
PageView.builder(
onPageChanged: (int index) {
setState(() {
_currentPageIndex = index % (pageList.length);
});
},
itemCount: 10000,
itemBuilder: (context, index) {
return _buildPageViewItem(pageList[index % (pageList.length)]);
},
),
Positioned(
bottom: 10,
left: 0,
right: 0,
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(pageList.length, (i) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 5),
width: 10,
height: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentPageIndex == i
? Colors.blue
: Colors.grey),
);
}).toList(),
),
),
),
],
),
),
);
}
_buildPageViewItem(String txt, {Color color = Colors.red}) {
return Container(
color: color,
alignment: Alignment.center,
child: Text(
txt,
style: TextStyle(color: Colors.white, fontSize: 28),
),
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
效果如下:
版权所有,禁止私自转发、克隆网站。