Flutter ListView如何添加HeaderView和FooterView


做過Android開發的同學知道,Android的ListView提供addHeaderView和addFooterView兩個方法用於添加View到ListView;
RecyclerView則通過定義不同的ItemType區分HeaderViewItem和普通的ListItem,在Adapter中加上邏輯判斷返回對應的ViewHolder,處理起來還是有點麻煩的。


而flutter的ListView怎么處理呢?有兩種方式:
  1. 參考RecyclerView的實現方式,定義不同類型的Item,如果想保持HeaderViewItem滾出屏幕外而不會被銷毀,需要使用KeepAlive控件對HeaderViewItem做一層包裹;
  2. 使用CustomScrollView + SliverToBoxAdapter + SliverList;

推薦使用方式2,實現簡單沒有多余的判斷邏輯處理,廢話少說,直接上代碼:

class MyHomePage extends StatelessWidget {

  // 列表項
  Widget _buildListItem(BuildContext context, int index){
    return ListTile(
      title: Text('list tile index $index')
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo'),
      ),
      body: CustomScrollView(
        slivers: <Widget>[
          // 如果不是Sliver家族的Widget,需要使用SliverToBoxAdapter做層包裹
          SliverToBoxAdapter(
            child: Container(
              height: 120,
              color: Colors.green,
              child: Text('HeaderView'),
            ),
          ),
          // 當列表項高度固定時,使用 SliverFixedExtendList 比 SliverList 具有更高的性能
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem, childCount: 30),
              itemExtent: 48.0
          )
        ],
      ),
    );
  }
}

 

運行效果:

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM