Flutter
Flutter - Scrollable with sliver
대기만성 개발자
2021. 6. 26. 00:59
반응형
특정 위치에 도달했을 때 스크롤을 멈추고 싶을 때
다른 방법도 있지만 scrollable을 이용하면 조금 더 편하게 작업할 수 있습니다
기본적으로 위젯의 포지션을 파악할 때 renderObject를 이용해서 위치를 계산하는데
(관련 예제 : https://devmemory.tistory.com/44)
Global key를 이용해서 간단하게 원하는 포지션에서 스크롤을 멈춰줄 수 있습니다
class ScrollableExample extends StatelessWidget {
ScrollableExample({Key? key, required this.title}) : super(key: key);
final String title;
final GlobalKey _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: CustomScrollView(slivers: [
SliverAppBar(
leading: IconButton(
icon: Icon(Icons.close, color: Colors.white),
onPressed: () {
Navigator.of(context).pop();
},
alignment: Alignment.center),
backgroundColor: Colors.black,
expandedHeight: size.height * 0.4,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
stretchModes: <StretchMode>[
StretchMode.fadeTitle,
],
background: Container(),
title: Text(title),
centerTitle: true,
),
),
SliverList(
delegate: SliverChildListDelegate([
IconButton(onPressed: (){
Scrollable.ensureVisible(_globalKey.currentContext!,
duration: Duration(milliseconds: 800));
}, icon: CircleAvatar(child: Icon(Icons.arrow_downward_sharp))),
SizedBox(
height: size.height * 0.5,
),
Center(child: Text('This!',key: _globalKey)),
SizedBox(
height: size.height * 0.5,
),
]),
)
]),
);
}
}
간단한 Sliver 앱바와 리스트인데
아이콘 버튼을 누르면 Scrollable의 ensureVisible static메소드를 사용할 수 있고
해당 설명을 읽어보면 역할을 파악할 수 있습니다
Scrolls the scrollables that enclose the given context so as to make the given context visible.
context가 적용된 위젯이 보일 때까지 스크롤 해줌 정도로 축약해볼 수 있을 거 같습니다
그런데 주의해야될점이 builder같은걸 사용할 경우 화면에 없을때 렌더링이 안돼서 그런건지
에러가 발생하고 작동하지 않는 경우가 있었는데 조금 더 테스트를 해봐야될거 같습니다
반응형