flutter3.0学习笔记

SliverList

Preview
  • SliverList

常用的 Sliver

SliverList

SliverListCustomScrollView 中实现,其构造:

const SliverList({
    super.key,
    required super.delegate,
});

delegate:SliverChildDelegate提供两个属性:

  • SliverChildListDelegate构造:
SliverChildListDelegate(
    this.children, {
    this.addAutomaticKeepAlives = true,
    this.addRepaintBoundaries = true,
    this.addSemanticIndexes = true,
    this.semanticIndexCallback = _kDefaultSemanticIndexCallback,
    this.semanticIndexOffset = 0,
  })
  • SliverChildBuilderDelegate适合数量大的列表
const SliverChildBuilderDelegate(
    this.builder, {
    this.findChildIndexCallback,
    this.childCount,
    this.addAutomaticKeepAlives = true,
    this.addRepaintBoundaries = true,
    this.addSemanticIndexes = true,
    this.semanticIndexCallback = _kDefaultSemanticIndexCallback,
    this.semanticIndexOffset = 0,
  })

完整例子:

import 'package:flutter/material.dart';

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

  @override
  State<CustomScrollViewPage> createState() => _CustomScrollViewPageState();
}

class _CustomScrollViewPageState extends State<CustomScrollViewPage> {
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverList(
             delegate: SliverChildBuilderDelegate(
                 (BuildContext context,int index){
                   return Card(
                     margin: const EdgeInsets.all(15),
                     child: Container(
                       color: Colors.purple[100 * (index%9+1)],
                       height: 80,
                       alignment: Alignment.center,
                       child: Text(
                         'Iitem $index',
                         style: const TextStyle(fontSize: 30),
                       ),
                     ),
                   );
                 },
               childCount: 1000,
             )
          )
        ],
       
      ),
    );
  }
}

image.png