简介
PageView 是一个滑动视图列表,它也是一个无状态的Widget。
class PageView extends StatefulWidget {
/// Creates a scrollable list that works page by page from an explicit [List]
/// of widgets.
///
/// This constructor is appropriate for page views with a small number of
/// children because constructing the [List] requires doing work for every
/// child that could possibly be displayed in the page view, instead of just
/// those children that are actually visible.
PageView({
Key key,
this.scrollDirection = Axis.horizontal, // 滚动方向
this.reverse = false, // 反转视图index
PageController controller, // 视图控制器
this.physics,
this.pageSnapping = true, // 弹性
this.onPageChanged,
List children = const [],
this.dragStartBehavior = DragStartBehavior.start,
}) : controller = controller ?? _defaultPageController,
childrenDelegate = SliverChildListDelegate(children),
super(key: key);
PageView简单用法
class PageViewDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return PageView(
// reverse: true,
// scrollDirection: Axis.vertical,
// pageSnapping: false,
controller: PageController(
initialPage: 2,
keepPage: false,
viewportFraction: 0.8,
),
onPageChanged: (currentPageIndex) =>
debugPrint('Page: $currentPageIndex'),
children: [
Container(
color: Colors.red,
alignment: Alignment(0.0, 0.0),
child: Text(
'第一个页面',
style: TextStyle(
color: Colors.white,
),
),
),
Container(
color: Colors.grey,
alignment: Alignment(0.0, 0.0),
child: Text(
'第二个页面',
style: TextStyle(
color: Colors.white,
),
),
),
Container(
color: Colors.green,
child: Text(
'第三个页面',
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
),
],
);
}
}
可配置的PageView.builder
class PageViewBuilderDemo extends StatelessWidget {
Widget _pageItemBuilder(BuildContext context, int index) {
return Stack(
children: [
SizedBox.expand(
child: Image.network(
posts[index].imageUrl,
fit: BoxFit.cover,
),
),
Positioned(
bottom: 20.0,
left: 20.0,
child: Column(
children: [
Text(
posts[index].title,
style: TextStyle(
color: Colors.red,
fontSize: 30.0,
),
),
Text(
posts[index].author,
style: TextStyle(
color: Colors.yellow,
fontSize: 25.0,
),
),
],
),
),
],
);
}
@override
Widget build(BuildContext context) {
return PageView.builder(
itemCount: posts.length,
itemBuilder: _pageItemBuilder,
);
}
}