Flutter의 Slivers 시리즈 구성 요소

목차

1. 슬리버 소개

둘, SliverList

1.SliverChildListDelegate

2.SliverChildBuilderDelegate 

3. 슬리버그리드

1.count 생성자는 SliverGrid를 설정합니다.

2. 범위 생성자는 SliverGrid를 설정합니다.

3. 기본 생성자는 SliverGrid를 설정합니다.

4. 슬리버앱바


머리말

        Flutter의 Sliver는 위젯 스크롤링과 관련된 일부 위젯입니다. 앱 개발 과정에서 스크롤 사용, 상품 정보 목록 표시, 최신 시세 새로 고침을위한 주식 풀다운 등을 볼 수 있습니다. 요약하면 표시할 콘텐츠의 길이가 현재 화면의 표시 범위를 초과할 때 스크롤 구성 요소를 사용합니다. 가장 일반적인 것은 ListView와 GridView입니다. 대부분의 경우 일반적인 ListView와 GridView는 기본적으로 사용자의 요구를 충족시킬 수 있으며 복잡한 애니메이션을 구현하려는 경우 Sliver 구성 요소가 유용합니다. 예를 들어 다음 애니메이션 효과는 Slivers를 사용하여 쉽게 달성할 수 있습니다.

        오늘의 기사는 주로 Sliver의 사용법을 설명하고 분석하는 것입니다.

1. 슬리버 소개

        개발 중에 ListView 및 GridView와 같은 대부분의 스크롤 가능한 보기는 실제로 Sliver를 사용하여 구현됩니다. ListView의 정의와 같은 소스 코드를 연구하십시오. 아래 스크린샷은 ListView의 정의에서 가져온 것입니다.

그림 3. ListView 정의

        GridView는 또한 다음과 같습니다.

 그림 4. GridView의 정의

        Sliver의 공식 설명은 다음과 같습니다: Slivers를 하위 수준의 인터페이스로 간주할 수 있습니다. Slivers를 사용하면 스크롤 영역을 보다 세밀하게 제어하여 다양한 효과를 얻을 수 있습니다. Slivers의 뷰는 필요할 때 빌드되고 렌더링되기 때문에 Slivers는 스크롤 가능한 영역에 많은 뷰가 있을 때 특히 효율적입니다.

        Flutter의 모든 슬리버 구성 요소는 CustomScrollView와 함께 사용되며 슬리버 구성 요소는 CustomScrollView의 하위 컨트롤로 사용됩니다. 일반적으로 사용되는 Sliver는 SliverList, SliverGridView, SliverAppBar입니다. 사용법은 아래에서 자세히 소개합니다.

둘, SliverList

        SliverList는 Delegate의 필수 매개변수를 가지고 있으며 Delegate는 SliverChildListDelegate와 SliverChildBuilderDelegate의 두 가지 유형이 있으며 차이점은 자식 컨트롤을 한 번에 빌드할지 여부입니다.

        간단한 예를 사용하여 두 델리게이트 간의 차이점을 확인할 수 있습니다.

1.SliverChildListDelegate

        예를 들어 SliverList를 사용하여 다음 렌더링과 유사하게 서로 다른 색상의 3개(또는 다른 숫자) 컨테이너를 표시하려고 합니다. 

 그림 5. 간단한 SliverList

        다음 코드를 사용하여 이를 수행할 수 있습니다.

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

  @override
  State<SliverForListPage> createState() => _SliverForListPageState();
}

class _SliverForListPageState extends State<SliverForListPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sliver用法',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [

          SliverList(delegate: SliverChildListDelegate([
            Container(color: getRandomColor(),height: 150,),
            Container(color: getRandomColor(),height: 150,),
            Container(color: getRandomColor(),height: 150,),
          ])),
        ],

      ),
    );
  }
}

        위의 코드에서 외부 레이어는 CustomScrollView를 사용하여 SliverList를 래핑합니다. Row와 Column을 사용했다면 둘의 사용법이 비슷하다는 것을 알 수 있는데 차이점은 Column과 Row에 표시되는 자식 컨트롤의 배열 이름을 children이라고 하는 반면 Slivers 시리즈 구성 요소는 slivers를 사용하여 표시할 컨트롤의 배열을 나타냅니다. 여기서 컨트롤을 만드는 SliverList의 효율성은 높지 않습니다. SliverChildListDelegate는 컨테이너를 한 번만 만들기 때문입니다.

2.SliverChildBuilderDelegate 

        표시할 컨트롤이 많은 경우 SliverChildBuilderDelegate를 사용하여 컨트롤 목록을 효율적으로 만들 수 있습니다. 다음 코드를 사용하여 무한 목록을 만들 수 있습니다. 컨트롤이 표시될 때만 생성되므로 매우 효율적입니다.

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

  @override
  State<SliverForListPage> createState() => _SliverForListPageState();
}

class _SliverForListPageState extends State<SliverForListPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sliver用法',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [
          SliverList(delegate: SliverChildBuilderDelegate((context, index) => Container(color: getRandomColor(),height: 150,))),
        ],

      ),
    );
  }
}

그림 6. 지연 로딩으로 SliverList 만들기    

3. 슬리버그리드

        SliverList와 마찬가지로 SliverGridView는 대리자를 표시하거나 사용하여 목록을 지정할 수 있습니다. SliverGridView를 구성하는 세 가지 방법이 있습니다.

1.count 생성자는 SliverGrid를 설정합니다.

        아래 코드를 사용하여 서로 다른 색상의 컨테이너 100개 목록을 만들 수 있습니다.

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

  @override
  State<SliverForGridViewPage> createState() => _SliverForGridViewPageState();
}

class _SliverForGridViewPageState extends State<SliverForGridViewPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  List<Widget> generateWidgetList(){
    List<Widget> list = [];
    for(var i = 0;i<100;i++){
      Container container =  Container(
        color: getRandomColor(),
        height: 150,
      );
      list.add(container);
    }
    return list;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SliverGrid.extent',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [
          SliverGrid.extent(maxCrossAxisExtent: 100,children: generateWidgetList(),),
        ],

      ),
    );
  }
}

그림 7. 카운트 생성자는 SliverGrid를 구현합니다. 

2. 범위 생성자는 SliverGrid를 설정합니다.

        다음 코드를 사용하여 서로 다른 색상의 컨테이너 100개를 만들 수 있으며 그 효과는 그림 8에 나와 있습니다.

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

  @override
  State<SliverForGridViewPage> createState() => _SliverForGridViewPageState();
}

class _SliverForGridViewPageState extends State<SliverForGridViewPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  List<Widget> generateWidgetList(){
    List<Widget> list = [];
    for(var i = 0;i<100;i++){
      Container container =  Container(
        color: getRandomColor(),
        height: 150,
      );
      list.add(container);
    }
    return list;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SliverGrid.extent',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [
          //这里构建了无限滚动的不同容器
          SliverGrid.extent(maxCrossAxisExtent: 100,children: generateWidgetList(),),
        ],

      ),
    );
  }
}

그림 8. 카운트 생성자는 SliverGrid를 구현합니다. 

3. 기본 생성자는 SliverGrid를 설정합니다.

        아래 코드를 사용하여 그림 9에 표시된 잘못된 스크롤 SliverGrid 그리드 보기를 만들 수 있습니다.

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

  @override
  State<SliverForGridViewPage> createState() => _SliverForGridViewPageState();
}

class _SliverForGridViewPageState extends State<SliverForGridViewPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SliverGrid.extent',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [
          //这里构建了无限滚动的不同容器
          SliverGrid(gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), delegate: SliverChildBuilderDelegate((context, index) => Container(
            color: getRandomColor(),
            height: 150,
          ))),
        ],

      ),
    );
  }
}

그림 9. SliverGrid를 지정하는 카운트 생성자 

4. 슬리버앱바

        여기에서는 글의 시작 부분에서 구현한 AppBar의 애니메이션 효과를 구현하는 방법을 살펴봅니다.

        위의 무한 스크롤 컨테이너 목록을 예로 들어 AppBar 대신 SliverAppBar를 사용하고, flexibleSpace 매개변수와 ExpandedHeight 매개변수를 동시에 설정하여 글 시작 부분의 효과를 구현합니다.코드는 다음과 같습니다.

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

  @override
  State<SliverForListPage> createState() => _SliverForListPageState();
}

class _SliverForListPageState extends State<SliverForListPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: const Text('SliverList',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
            backgroundColor: Colors.blue,
            flexibleSpace: FlexibleSpaceBar(
              background: Image.asset('images/header.jpeg',fit: BoxFit.cover,),
            ),
          ),
          SliverList(delegate: SliverChildBuilderDelegate((context, index) => Container(color: getRandomColor(),height: 150,))),
        ],

      ),
    );
  }
}

         달성한 효과는 다음과 같습니다.

            

 그림 10. SliverApp 효과

       이때 아래 목록과 함께 SliverAppBar가 스크롤되는 것을 확인할 수 있습니다. 풀다운 시, ExpandedHeight 매개변수를 초과하면 SliverAppBar가 표시되고, 위로 밀면 SliverAppBar가 사라질 때까지 목록과 함께 슬라이드됩니다.

       일부 매개 변수를 설정하여 AppBar 애니메이션 효과를 사용자 지정할 수도 있습니다.

        부동 매개변수를 true로 설정하면 변경 사항을 확인합니다(그림 11). 시간을 아래로 스크롤할 때 SliverAppBar가 목록의 맨 위에 있지 않은 경우에도 나타납니다.

        

 그림 11. SliverAppBar

        스냅 및 부동 매개변수를 동시에 true로 설정하면 아래로 스크롤할 때 SliverAppBar가 자동으로 다시 표시됩니다(그림 12).

 그림 13. SliverAppBar

        물론 자신의 AppBar 애니메이션 효과를 구현하기 위해 자신의 필요에 따라 다른 매개변수를 설정할 수 있습니다.

        이 기사를 읽은 후 기사 시작 부분에서 SliverList, SliverGrid 및 SliverAppBar를 결합하여 그룹화 효과를 달성하는 방법에 대해 생각할 수도 있습니다. 행운을 빌어요!

추천

출처blog.csdn.net/ZCC361571217/article/details/129541042