[Flutter] ListView()

Tyger·2021년 10월 13일
2

ListView()

 ListView({
    Key? key,
    Axis scrollDirection = Axis.vertical,
    bool reverse = false,
    ScrollController? controller,
    bool? primary,
    ScrollPhysics? physics,
    bool shrinkWrap = false,
    EdgeInsetsGeometry? padding,
    this.itemExtent,
    bool addAutomaticKeepAlives = true,
    bool addRepaintBoundaries = true,
    bool addSemanticIndexes = true,
    double? cacheExtent,
    List<Widget> children = const <Widget>[],
    int? semanticChildCount,
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
    ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
    String? restorationId,
    Clip clipBehavior = Clip.hardEdge,
  }) 

flutter로 실재 App을 개발하면 가장 자주 쓰이는 widget 중 하나가 바로 ListView() 위젯이다.

ListView는 list형식의 데이터를 쉽게 보여주는 위젯으로 ListView.builder(), ListView.custom(), ListView.separated()의 종류로 다양하게 사용할 수 있다

여기서는 ListView 안에 children과 ListView.builder()만 살펴보겠다

먼저 데이터는 국가 영문/국문으로 정리된 Map형태의 데이터를 사용함

Map은 아래와 같이 key, value로 정리된 구조의 데이터 타입이다

class NationDataList {
  final Map<String, String> nation = {
    'GHANA': "가나",
    'GABON': "가봉",
    'GUYANA': "가이아나",
    'GAMBIA': "감비아",
    'GUERNSEY': "건지 섬",
    'GUADELOUPE': "과들루프",
    ...
  }
}

기본 ListView()는 children 안에 widget을 넣어서 사용할 수 있고, List나 Map 형태의 자료를
쉽게 사용하기 위해서 ...을 사용하면 안에 있는 데이터를 바로 아래처럼 사용 가능하다

..., .. 연산자는 다른 블로그를 보면 쉽게 설명이 되어있으며, flutter의 필수 연산자라 생각한다

index값에 접근하고 싶다면 ListView.builder()를 사용하는 것을 추천함

...map(e)를 통해서 key, value의 값을 사용 가능하고 widget은 각 개별 index값에 대한 widget이므로 ListView의 UI를 제어하고 싶으면 ListView를 감싸서 사용 하면됨

shrinkWrap은 기본 false이고, ListView를 screen전체에서 사용할 시에는 기본 값을 두고도 사용 가능하지만 ListView외에 다른 위젯이 같은 스크린 내에 있을 시에는 shrinkWrap을 true로 하거나 Flexible, Expanded, SizedBox와 같은 크기를 제어할 수 있는 widget을 사용해서 크기를 정의해 주어야 한다

shrinkWrap을 true로 하면 ListView 내에서만 스크롤이 되는 문제가 있어 body를 SingleChildScrollView()로 감싼 후 ListView 속성 값인 physics를 사용해서 스크롤을 잠그거나 활성화 시켜서 사용할 수 있다

ListView(
   shrinkWrap: true,
   children: [
     ...NationDataList().nation.entries.map((e) => Padding(
           padding: const EdgeInsets.symmetric(
               horizontal: 20, vertical: 12),
                 child: Row(
                   children: [
                      SizedBox(
                        width: size.width * 0.45,
                         child: Text(
                           e.key, overflow: TextOverflow.ellipsis,)),
             SizedBox(
                     width: size.width * 0.45,
                  child: Text(e.value,
                          overflow: TextOverflow.ellipsis,
                   )),
              ],
           ),
            )),
    ],
 ),

앞서 설명한 것처럼 physics: NeverScrollableScrollPhysics()를 하게되면 listview 안에서의
scroll을 막고 body에 있는 scroll을 사용하게 된다

ScrollPhysics() widget에 대해서도 다음에 다뤄볼 예정이다

ListView(
   physics: const NeverScrollableScrollPhysics(),
   shrinkWrap: true,
    children: [
     ...NationDataList().nation.entries.map((e) => Padding(
           padding: const EdgeInsets.symmetric(
             horizontal: 20, vertical: 12),
               child: Row(
                children: [
                  SizedBox(
                    width: size.width * 0.45,
                     child: Text(e.key,overflow: TextOverflow.ellipsis,)),
                      SizedBox(
                         width: size.width * 0.45,
                           child: Text(
                            e.value,
                          overflow: TextOverflow.ellipsis,
                       )),
                     ],
            ),
    )),
 ],
),

ListView.builder()는 index 값을 제어하면서 사용 가능하다
index값에 따른 UI가 변하거나 index값이 필요한 경우에는 builder를 사용해서 작업을함

ListView.builder()는 flutter에 있는 다른 builder들과 사용하는 것은 똑같다
builder에 필수로 context, index의 값을 받아야하고 itemCount에 count 값을 줘야한다

아래는 간단하게 100개의 index 값을 사용해서 만들었으며, List 자료형을 사용할 때는 List.length 값으로 count 값을 주면됨

index는 0부터 카운트 됨

scrollDiretion은 list를 수평적, 수직적으로 보여줄 수 있으며, Axis.vertical은 수직적, Axis.horizontal은 수평적으로 list를 보여준다 (Default 값은 vertical)

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: 100,
  itemBuilder: (context, index) {
  return Padding(
     padding: const EdgeInsets.all(8.0),
        child: Text(index.toString()),
 );
}),

Example

profile
Flutter Developer

0개의 댓글