Flutter에서 페이지를 스크롤하여 보여주는 데 사용되는 위젯
페이지를 지정된 리스트로부터 렌더링하기 때문에 주로 페이지 수가 적거나 고정된 경우에 사용
(모든 페이지가 동시 렌더링되어 메모리 소비가 높아질수있다)
return PageView(
scrollDirection: Axis.vertical,
children: [
Container(
color: Colors.blue,
),
Container(
color: Colors.teal,
),
Container(
color: Colors.yellow,
),
Container(
color: Colors.pink,
)
],
);
페이지를 빌더 힘수를 통해 동적으로 생성
itemBuilder 메소드를 통해 context와 현재 render할 항목의 index를 인자로 받는다
데이터베이스에서 페이지를 가져와 보여줄때 유용
필요한 페이지만 레더링되기 때문에 메모리를 효율적으로 사용할 수 있다
class _VideoTimelineScreenState extends State<VideoTimelineScreen> {
List<Color> colors = [
Colors.blue,
Colors.red,
Colors.yellow,
Colors.teal,
];
Widget build(BuildContext context) {
return PageView.builder(
scrollDirection: Axis.vertical,
itemCount: 4,
itemBuilder: (context, index) => Container(
color: colors[index],
),
);
}
}
PageView.builder를 사용하여 세로로 스크롤하는 페이지를 만드는 방법을 간단하게 작성
_itemCount
는 현재 보여지는 페이지 개수를 나타내는 변수
colors
각 페이지에 대한 색상을 저장하는 리스트
onPageChanged
페이지가 변경될대 호출되는 콜백함수로
마지막 페이지에 도달하면 _itemCount를 4만큼 증가시키고 colors 리스트에도 새로운 색상을 추가하여 확장
마지막에 setState((){})상태업데이트를 하고 화면을 다시 그리도록 한다
int _itemCount = 4;
List<Color> colors = [
Colors.blue,
Colors.red,
Colors.yellow,
Colors.teal,
];
void _onPageChanged(int page) {
if (page == _itemCount - 1) {
_itemCount = _itemCount + 4;
colors.addAll([
Colors.blue,
Colors.red,
Colors.yellow,
Colors.teal,
]);
setState(() {});
}
}
Widget build(BuildContext context) {
return PageView.builder(
scrollDirection: Axis.vertical,
onPageChanged: _onPageChanged,
itemCount: _itemCount,
itemBuilder: (context, index) => Container(
color: colors[index],
),
);
}