Flutter - #19. SliverList

Pearl Lee·2021년 6월 17일
1

Flutter Widget

목록 보기
19/50

내가 보려고 쓰는 Flutter 일기
참고1 : https://api.flutter.dev/flutter/widgets/SliverList-class.html
참고2 : https://medium.com/flutter/slivers-demystified-6ff68ab0296f








SliverList

오늘은 지난 시간 SliverAppBar에 이어서 SliverList를 배워보자.
이름에서 알 수 있듯 List 형태로 위젯들을 나타내주며, 생긴거나 쓰는거나 ListView와 별반 다를 바 없어보인다. 착각인가

SliverList를 생성하는 두가지 방법에 대해 알아보자. 하나는 SliverList, SliverChildListDelegate 를 이용할 것이고, 다른 하나는 SliverFixedExtentListSliverChildBuilderDelegate를 이용한 것이다.

꼭 두개 두개 묶어서 쓰는게 아니라 교차해서 써도 된다! 그런데 내 생각에는 아마 두번째 경우를 더 자주 이용할 것 같다.
저번시간에 돌려본 코드를 바탕으로 할 것이다.

우선, 리스트에 표시될 요소들은 delegate 속성에 설정한다는 것을 알아두고 내려가보자.











코드 예시로 알아보자

SliverList, SliverChildListDelegate

저번 일기에서 돌려본 코드를 가져와 살짝만 변형해보았다. AppBar부분은 동일하다.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Test CustomScrollView'),
        ),
        body: CustomScrollView(
          slivers: <Widget>[
            const SliverAppBar(
              pinned: true,
              expandedHeight: 200.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('SliverAppBar'),
                background: FlutterLogo(),
              ),
            ),
            
            SliverList(
              delegate: SliverChildListDelegate([
                Container(color: Colors.red, height: 150.0),
                Container(color: Colors.purple, height: 100.0),
                Container(color: Colors.green, height: 200.0),
              ]),
            ),
          ],
        ));
  }
}

delegate에 SliverChildListDelegate 로 화면에 표시될 위젯들을 설정한다. 위젯들의 높이는 정해진게 없어서, 따로따로 설정이 가능하다. 그리고 자식 요소들을 하나하나 넣어주었다. 실행화면은 아래와 같다.



height: 150,50,200height: 100




항목별로 높이를 다르게 하는 거까진 좋은데, 보통은 목록에서 항목별 높이가 같은 경우가 많을 것이다.
그렇다면 이제 SliverFixedExtentList로 넘어가보자.










SliverFixedExtentList, SliverChildBuilderDelegate

SliverList 부분을 지우고 요렇게 바꿔보도록 하겠다. (저번시간에 표시된 화면과 똑같다.)

            SliverFixedExtentList(
              itemExtent: 50.0,
              delegate:
                  SliverChildBuilderDelegate((BuildContext context, int index) {
                return Container(
                  alignment: Alignment.center,
                  color: Colors.purple[100 * (index % 10)],
                  child: Text(
                    'List Item $index',
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                );
              }, childCount: 10),
            ),




itemExtent: 50.0itemExtent: 100.0




SliverFixedExtentList - extent(크기)를 고정시켜 놓는다는 것이다.
세로 방향 리스트에서 크기라고 할 건 높이밖에 없으니까, 항목별 높이를 같게 하는 것과 같다. 따라서 반드시 itemExtent와 같이 써주어야 한다.

SliverChildBuilderDelegate는 ListView.builder와 상당히 유사하게 생겼다. 인자로 들어가는 index값이 childCount보다 작은 동안 함수가 계속 실행되어 목록을 만드는 것이다. SliverChildListDelegate에서 자식 요소 코드를 일일이 적어주던 것과 달리, 똑같은 자식을 여러개 찍어내는 것이다.




그런데 childCount속성을 설정하지 않으면 어떻게 될까? 자식 수에 제한을 두지 않으면...? 계속 만들어낸다. 궁금해서 1000번째 자식 넘어갈 때까지 스크롤을 내려보았다.


childCount: 10childCount 지정 안함




1000번째 항목을 가뿐히 넘어간다. 끝이 어딘지 궁금하긴 한데 1000개 이상의 항목을 로드하는 앱은 거의 없을...거라고 생각해




오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글