민프

[Flutter] showModalBottomSheet(바텀시트)를 사용해보자 본문

[Flutter]

[Flutter] showModalBottomSheet(바텀시트)를 사용해보자

민프야 2023. 9. 8. 14:40

Flutter 개발을 할 때마다 느끼는거지만 개발 시간을 줄이기 위한 기본 위젯들이 잘 되어있다고 생각합니다.

이번 포스팅에서는 Flutter BottomSheet를 적용해보려고 합니다.

 

먼저 결과 화면을 봐볼까요?

위 영상에서 댓글 아이콘을 누르면 BottomSheet가 잘 나오는 것을 확인할 수 있습니다.

위 BottomSheet를 아래 예시 코드를 입력하면 쉽게 구현할 수 있습니다.

  void _onCommentsTap(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(),
    );
  }
.
.
.  
   GestureDetector(
      onTap: () => _onCommentsTap(context),
      child: const VideoButton(
        icon: FontAwesomeIcons.solidComment,
        text: "330k",
      ),
   ),

개발 문서에 의하면

Future<T?> showModalBottomSheet<T>(
{required BuildContext context,
required WidgetBuilder builder,
Color? backgroundColor,
String? barrierLabel,
double? elevation,
ShapeBorder? shape,
Clip? clipBehavior,
BoxConstraints? constraints,
Color? barrierColor,
bool isScrollControlled = false,
bool useRootNavigator = false,
bool isDismissible = true,
bool enableDrag = true,
bool? showDragHandle,
bool useSafeArea = false,
RouteSettings? routeSettings,
AnimationController? transitionAnimationController,
Offset? anchorPoint}
)

showModalBottomSheet는 Future을 반환하는 것을 확인할 수 있었는데요.

즉, await를 사용할 수 있다는 것 입니다.

그렇다면 Botttom이 내려가고 난 후 작업 정의를 쉽게 할 수 있다는 것인데

그럼 BottomSheet가 올라갔을 땐 동영상을 정지시키고, 내려갔을때 다시 재생시키는 로직을 구현해보겠습니다.

  void _onCommentsTap(BuildContext context) async {
    if (_videoPlayerController.value.isPlaying) {
      _onTogglePause();
    }
    await showModalBottomSheet(
      context: context,
      builder: (context) => const VideoComments(),
    );
    _onTogglePause();
  }

위 의 코드와 다른 점은 async, await가 들어간 것과 버텀이 내려가고나서 로직이 추가 된 부분입니다.

아래 결과 화면을 보시면 댓글창이 위로 올라왔을 때 영상이 멈추고, 내려갔을 때 영상이 다시 재생되는 것을 확인하실 수 있습니다.  

이 외 BottomSheet 설정 값들을 보면

뒷 배경 색상을 정해주는 barrierColor

배경색상을 정해주는 backgroundColor 등등.. 옵션들이 있는데 

 

만약 BottomSheet안에 ListView 나 GridView를 사용하면서 버텀의 height를 바꿔주고싶다면

isScrollControlled 를 True로 바꿔주면 됩니다. (개발 문서에 나와있는 내용)

isScrollControlled 설정 값에 대해서 예시 코드와 결과 화면은 아래와 같습니다.

  void _onCommentsTap(BuildContext context) async {
    if (_videoPlayerController.value.isPlaying) {
      _onTogglePause();
    }
    await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => const VideoComments(),
    );
    _onTogglePause();
  }
  .
  .
  .
   return Container(
      height: size.height * 0.7,


참고문서

https://api.flutter.dev/flutter/material/showModalBottomSheet.html

 

showModalBottomSheet function - material library - Dart API

Future showModalBottomSheet ({required BuildContext context, required WidgetBuilder builder, Color? backgroundColor, String? barrierLabel, double? elevation, ShapeBorder? shape, Clip? clipBehavior, BoxConstraints? constraints, Color? barrierColor, bool isS

api.flutter.dev

 

Comments