[flutter] ListView, GridView

jini.choi·2024년 3월 12일
0

flutter

목록 보기
2/9

ListView

  • 여러 위젯을 세로나 가로로 나열하면서 화면을 벗어날 때 스크롤을 지원하고자 사용
  • 일반 목록 화면처럼 항목을 나열할 때 사용

스크롤 지원 ListView

  • 기본적으로 플러터 앱은 위젯이 화면을 벗어날 때 스크롤을 지원하지 않으면 경고 영역으로 보여진다.
  • 이때 스크롤이 지원되는 ListView로 바꾸면 스크롤 경고 영역이 사라진다.
    • 기본적으로 세로로 나열된다.
ListView(
	children: [
  		Contaiter(height: 300, color: Colors.red,),
  		Contaiter(height: 300, color: Colors.green,),
  		Contaiter(height: 300, color: Colors.blue,),
  ],
)
  • 가로로 나열할 경우
ListView(
  	scrollDirection: Axis.horizontal
	children: [
  		Contaiter(height: 300, color: Colors.red,),
  		Contaiter(height: 300, color: Colors.green,),
  		Contaiter(height: 300, color: Colors.blue,),
  ],
)

ListViewSingleChildScrollView + Column 조합과 차이점

  • ListView : 똑같은 형태의 항목을 세로로 출력하는 것에 최적화된 위젯, 따라서 같은 타입의 위젯들을 비슷한 형태로 출력해야하면 이게 편함
  • SingleChildScrollView + Column : 다양한 형태의 위젯들이라면 이게 편함

목록 구성

ListView()

  • 둘다 똑같은 화면을 만들 수 있지만 ListView()는 좀 비효율적이다.
  • 만약 100개의 항목이 있고 처음 리스트뷰가 나올 때 4개만 보인다면 아직 보이지 않는 96개 항목까지 모두 준비해야된다.

ListView.builder()

  • 항목이 많더라도 초기화면에 보일 항목만 구성하고 나머지는 사용자가 스크롤할 때 준비해서 나오게 한다.

  • ListView.builder() 생성자에는 itemCountitemBuilder 속성 설정

    • itemCount: 리스트 뷰에 출력할 항목 수 정하는 속성
    • itemBuilder : 항목을 구성하는 위젯을 만들어 주는 함수. 이 함수에서 반환한 위젯이 각 항목에 출력됨
List<String> citys = [
	'가','나','다','라','마','바',
];

@override
Widget build(BuildContext context) {
	return ListView.builder(
    	itemCount: citys.length,
      	itemBuilder: (context, index){
      		return Contaiter(
              padding: EdgeInsets.only(left: 10, top: 10,),
              height: 200,
              child: Text(citys[index]),
            ),
    	}
    )
}

ListView.seperated()

  • seperatorBuilder 속성에 지정하는 함수에서 구분자로 사용할 위젯을 준비하면 자동으로 반환한 위젯이 구분자로 출력
  • 주로 Divider 위젯 사용한다.
ListView.seperated(
    itemCount: citys.length,
    itemBuilder: (context, index){
      	return Contaiter(
             padding: EdgeInsets.only(left: 10, top: 10,),
             height: 200,
             child: Text(citys[index]),
          ),
   },
   seperatorBuilder: (context, index){
   		return Divider(height: 2, color: Colors.black,);
   },
)

항목 구성

ListTitle()

  • 항목을 구성하는 위젯

  • 문자열 왼쪽에는 이미지, 오른쪽에는 아이콘, 위아래로 텍스트이런 구성을 할 때 쓰면 편하다.

  • ListTitle 생성자에는 title, subtitle, leading, trailing 등의 속성이 있다.

  • 다음과 같은 구성을 할 수 있다.

ListView.seperated(
    itemCount: users.length,
    itemBuilder: (context, index){
      return ListTitle(
      	leading: CircleAvatar(
      		radius: 25,
        	backgroundImage: AssetImage('images/big.jpeg'),
      	),
        title: Text(users[index].name),
        subtitle: Text(users[index].phone),
        trailing: Text(users[index].more_vert),
        onTap: (){
        	print(users[index].name);
        }
      ),
   },
   seperatorBuilder: (context, index){
   		return Divider(height: 2, color: Colors.black,);
   },
)

GridView

  • 가로, 세로 방향으로 나열하지 않고 한 줄에 여러개를 나열할 때 사용한다.

  • 리스트뷰처럼 GridView.builder()생성자를 제공하고 itemCountitemBuilder 속성으로 이루어진다.

    • itemCount: 그리드 뷰에 출력할 항목 수 정하는 속성
    • itemBuilder : 항목을 구성하는 위젯을 만들어 주는 함수. 이 함수에서 반환한 위젯이 각 항목에 출력됨
  • 꼭! gridDelegate 속성을 설정해줘야한다.

    • 이 속성에는 SliverGridDelegateWithFixedCrossAxisCount 객체를 지정해주면되는데, 이 객체의 crossAxisCount값이 한 줄에 함께 나와야하는 개수이다.
  • 그리드 뷰에 방향을 지정하지 않으면 항목을 세로로 나열하며 이때 crossAxisCount는 가로를 가리킨다.

  • 만약 항목을 가로로 나열하려면 scrollDirection 속성에 Axis.horizontal이라고 설정하면 세로를 가리킨다.

세로로 배치

GridView.builder(
	itemCount: citys.length,	
    itemBuilder: (context, index) {
		return Card(
        	child: Text(citys[index]),
        );
	
},
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
)

가로로 배치

GridView.builder(
	itemCount: citys.length,	
    itemBuilder: (context, index) {
		return Card(
        	child: Text(citys[index]),
        );
	
},
  scrollDirection: Axis.horizontal,
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
)
profile
개발짜🏃‍♀️

0개의 댓글