SliverPersistentHeaderコンポーネントはFlutterの天井効果を実現します

効果:

20230723-212152-73_トリム

コード:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class StickHeaderPage extends StatefulWidget {
    
    

  
  State<StatefulWidget> createState() {
    
    
    // TODO: implement createState
    return _StickHeaderPageState();
  }

}

class _StickHeaderPageState extends State<StickHeaderPage> {
    
    

  
  Widget build(BuildContext context) {
    
    
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: const Text("Sticky Header"),
      ),
      body: CustomScrollView(
        slivers: [
          _topWidget(),
          _stickyHeader(),
          _listView(),
        ],
        physics: const BouncingScrollPhysics(),
      ),
    );
  }

  Widget _topWidget() {
    
    
    return SliverToBoxAdapter(
      child: Container(
        child: Image.network("https://2sc2.autoimg.cn/escimg/g27/M04/5D/0B/f_900x675_0_q87_autohomecar__ChxkmWMVdMCAJZdZAAFU8OPC7Xs588.jpg",
        ),
      ),
    );
  }

  Widget _stickyHeader() {
    
    
    return SliverPersistentHeader(
      pinned: true,
      floating: true,
      delegate: _StickyHeaderDelegate(
        minHeight: 50,
        maxHeight: 50,
        child: Container(
          height: 100,
          color: Colors.blue,
          alignment: Alignment.centerLeft,
          child: const Text("Sticky Header", style: TextStyle(fontSize: 20),),
        ),
      ),
    );
  }

  Widget _listView() {
    
    
    return SliverList(
      delegate:
        SliverChildBuilderDelegate( (context, index) {
    
    
          return Container(
              height: 50,
              color: index % 2 == 0 ? Colors.white : Colors.black12,
              width: double.infinity,
              alignment: Alignment.center,
              child: Text("Item $index"),
            );
        },
        childCount: 50,
      )
    );
  }

}

class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
    
    

  _StickyHeaderDelegate({
    
    
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    
    
    // TODO: implement build
    return SizedBox.expand(child: child,);
  }

  
  // TODO: implement maxExtent
  double get maxExtent => maxHeight;

  
  // TODO: implement minExtent
  double get minExtent => minHeight;

  
  bool shouldRebuild(covariant _StickyHeaderDelegate oldDelegate) {
    
    
    // TODO: implement shouldRebuild
    return (
        maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child
    );
  }


この記事の参照元: https://www.jianshu.com/p/b5292ef7c38c

おすすめ

転載: blog.csdn.net/kicinio/article/details/131884615