프론트엔드/Flutter

flutter 스크롤 기능 구현

곰돌이쿤 2024. 7. 17. 09:47
반응형

 

 

body: Column(
  children: [
    Container(
      width: MediaQuery.of(context).size.width,
      height: 300,
      color: Colors.green,
    ),
    Container(
      width: MediaQuery.of(context).size.width,
      height: 300,
      color: Colors.green,
    ),
    Container(
      width: MediaQuery.of(context).size.width,
      height: 300,
      color: Colors.green,
    ),
    Container(
      width: MediaQuery.of(context).size.width,
      height: 300,
      color: Colors.green,
    )
  ],
)

flutter 에서는 다음과 같이 화면이 넘어가게 되면 에러를 냄

 

이런 경우 scrollview 를 추가해주면 됩니다.

body: SingleChildScrollView(
  child: Column(
    children: [
      Container(
        width: MediaQuery.of(context).size.width,
        height: 300,
        color: Colors.green,
      ),
      Container(
        width: MediaQuery.of(context).size.width,
        height: 300,
        color: Colors.green,
      ),
      Container(
        width: MediaQuery.of(context).size.width,
        height: 300,
        color: Colors.green,
      ),
      Container(
        width: MediaQuery.of(context).size.width,
        height: 300,
        color: Colors.yellow,
      )
    ],
  ),
)

 

이미 비슷한걸 많이 봤겠지만 

SingleChildScrollView(
  child: Column 
위 코드를 ListView 로만 바꾸어도 동작하게 됩니다. 



scrollowView 를 여러 부분으로 나누고 싶다면 SizedBox 라는 위젯으로 분리하게 되면 스크롤뷰 부분을 따로 나눌 수 있습니다.

body: SingleChildScrollView(
          child: Column(
            children: [
              buildSizedBox(context),
              buildSizedBox(context),
              buildSizedBox(context),
            ]
          ),
        )
       ...

SizedBox buildSizedBox(BuildContext context) {
    return SizedBox(
              height: MediaQuery.of(context).size.height / 3,
              child: SingleChildScrollView(
                  child: Column(
                      children: [
                        Container(
                          width: MediaQuery.of(context).size.width,
                          height: 300,
                          color: Colors.green,
                        ),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          height: 300,
                          color: Colors.yellow,
                        )
                      ]
                  )
              ),
            );

코드 량이 길어져 하나로

반응형