플러터의 PageView를 사용해 봅시다
나는 원하는건 바텀 네비게이터를 누르면 페이지를 부드럽게 전환시켜주고 싶었다.
이럴때는 PageView를 쓰면 알아서 부드럽게 전환 가능하게 해준다고 한다.
PageView를 사용하면 controller를 통해서 페이지를 제어할 수 있다.
controller를 하나 만들어서 이렇게 넣어주면 된다.
이 pageController를 통해서 pageView가 보여줄 영역을 커스텀 할 수 있다.
PageView(
controller: pageController,
children: [
SizedBox.expand(
child: Container(
color: Colors.red,
child:
Text('첫번째 페이지'),
)
),
SizedBox.expand(
child: Text('두번쨰 페이지'),
)
],
),
대충 이런식으로 body에 PageView를 넣어봤다.
children의 요소를 통해서 PageView에 보일것을 넣을 수 있다.
final PageController pageController = PageController(
initialPage: 0,
);
찾아보니까 다음과 같은 요소들이 있다.
initialPage -> int : 처음에 보일 페이지
page -> double : 페이지뷰에서 현재 페이지의 위치. 페이지뷰가 길~게 늘여뜨려서 double값으로 위치를 표시하는거 같았다.
keepPage -> bool : 화면 전환이 되었을때 이전의 스크롤 위치를 기억하게 함
뭐 이런것들이 있는데 page는 직접 조작을 하지 못하도록 read-only가 되있었다.
그래서 함수를 보니까 몇가지 함수가 있었다.
한번에 점프하는 함수들
jumpTo(double value)
* value로 페이지뷰를 점프
jumpToPage(int page)
- 페이지로 페이지뷰를 점프
nextPage(required Duration, required Curve)
- 다음 페이지로 점프
이동하는 함수들
이동할때는 Duration(시간) 과 Curve(움직이는 방법)이 필요하다
Duration은 seconds, hours, miliseconds등등 ctrl + space를 누르면 뜨는걸로 간단하게 확인해볼 수 있고
Curve class는 여기서 자세하게 볼 수 있었다.
https://api.flutter.dev/flutter/animation/Curves-class.html
Curves class - animation library - Dart API
A collection of common animation curves. See also: Curve, the interface implemented by the constants available from the Curves class. Constructors Curves() Properties hashCode → int The hash code for this object. read-onlyinherited runtimeType → Type A
api.flutter.dev
animateTo(double offset, {required Duration, required Curve})
- offset만큼 페이지를 "이동"
animateToPage(int Page, {required Duration, required Curve})
- ~번 페이지로 "이동"
나는 원하는건 바텀 네비게이터를 누르면 페이지를 부드럽게 전환하는거니깐 animateToPage를 쓰면 된다.
https://api.flutter.dev/flutter/widgets/PageView-class.html
PageView class - widgets library - Dart API
A scrollable list that works page by page. Each child of a page view is forced to be the same size as the viewport. You can use a PageController to control which page is visible in the view. In addition to being able to control the pixel offset of the cont
api.flutter.dev
bottomNavigationBar:
BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
onTap: (i){
setState(() {
pageController.animateToPage(i, duration: Duration(milliseconds: 700), curve: Curves.ease);
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
label:"home"
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_bag_outlined),
label:"where"
),
]
)
바텀 네비게이터 바에 onTap을 사용했다. 누른 요소의 번호가 i에 들어가 있다.
pageController에서 animateToPage함수를 사용해서 i번째 페이지로 이동하게 하면
0.7초동안 ease라는 방식으로 i번째 페이지로 이동하게 된다.
성공!
'Flutter' 카테고리의 다른 글
[Flutter] Image 표시하기 (0) | 2023.06.15 |
---|