flutter _ SliverChildBuilderDelegate()

한별onestar·2023년 7월 24일

flutter

목록 보기
13/17
post-thumbnail

SliverChildBulderDelegate 클래스

빌더 콜백을 사용하여 슬리버에 대한 자식을 제공하는 대리자.


저번 flutter _ CustomScrollView 에서 SliverList에서 delegate속성을 SliverChildListDelegate로 작성하여 자식 요소를 하나하나 넣어 리스트를 생성했다. 그치만 이건 코드가 뭔가 이상하다. 그래서 바꿔줄 속성을 알아냈다!


SliverChildBuilderDelegate

인자로 들어가는 index값이 childCount보다 작은 동안 함수가 계속 실행되어 목록을 만든다. 똑같은 자식을 여러개 출력한다.

class Main extends StatelessWidget {
	final List<String> category = <String>['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
    //문자열의 리스트 변수 생성
    
    @override
    Widget build(BuildContext context) {
    	body: CustomScrollView(
        	slivers: <Widget>[
            	SliverList(
           		 delegate: SliverChildBuilderDelegate(
              		childCount: category.length,
                    //배열의 길이만큼만 출력
                    
                	(BuildContext context, int index) {
                  		return Container(
                    	padding: EdgeInsets.all(10),
                    	child: Row(
                     	 children: [
                        	Image.asset('assets/images/cloud.jpg', width: 32,),
                        	Text('${category[index]}', style: TextStyle(fontSize: 20),),
                            //문자열의 배열안의 데이터값을 순서대로 출력한다.
                      				],
                    			),
                  			);
                		}
            		),
          		)
            ]
        )
    }
}
  • 결과



이미지도 텍스트와 마찬가지로 변수를 선언해주고 불러오면 아이콘이 각각 Index에 맞게 변경된다!

final List<String> categoryIcon = <String>[
	'파일경로/파일이름(png, jpg ...)',
    '파일경로/파일이름(png, jpg ...)',
    '파일경로/파일이름(png, jpg ...)',
    '파일경로/파일이름(png, jpg ...)',
    '파일경로/파일이름(png, jpg ...)',
    '파일경로/파일이름(png, jpg ...)'
  ];
  
  
  
  /*
  위 코드에서 children 부분만 가져왔다.
  
  이렇게 하면 카테고리 이름 앞에 아이콘이 각각의 이름에 맞는 아이콘으로 변경된다!
  */
  children: [
  	Image.asset('${categoryIcon[index]}', width: 32,),
    Text('${category[index]}', style: TextStyle(fontSize: 20),),
		],




그치만 이 경우에 이미지 갯수와 텍스트의 갯수가 다르면 에러가 뜨게된다. 그리고 이미지 배열과 텍스트 배열의 순서가 같아야한다! 더 공부해서 다른 방법도 찾아봐야지

profile
한별잉

0개의 댓글