SliverAppBar控件可以實現頁面頭部區域展開、折疊的效果,類似於Android中的CollapsingToolbarLayout。
先看下SliverAppBar實現的效果,效果圖如下:
SliverAppBar控件需要和CustomScrollView搭配使用,SliverAppBar要通常放在slivers的第一位,后面接其他sliver控件。
CustomScrollView( slivers: <Widget>[ SliverAppBar( ), //其他sliver控件 ], )
SliverAppBar和其他slivers控件的結構如下:
SliverAppBar中有一個非常重要的參數flexibleSpace,flexibleSpace是SliverAppBar中展開和折疊區域,flexibleSpace與expandedHeight一起使用,
expandedHeight表示flexibleSpace的高度,
SliverAppBar( expandedHeight: 200.0, flexibleSpace: FlexibleSpaceBar( ), ),
SliverAppBar其他常用屬性說明如下:
屬性 | 說明 |
leading | 左側控件,通常情況下為"返回"圖標 |
title | 標題,通常為Text控件 |
actions | 右側控件 |
flexibleSpace | 展開和折疊區域 |
bottom | 底部控件 |
elevation | 陰影 |
expandedHeight | 展開區域的高度 |
floating | 設置為true時,向下滑動時,即使當前CustomScrollView不在頂部,SliverAppBar也會跟着一起向下出現 |
pinned | 設置為true時,當SliverAppBar內容滑出屏幕時,將始終渲染一個固定在頂部的收起狀態 |
snap | 設置為true時,當手指放開時,SliverAppBar會根據當前的位置進行調整,始終保持展開或收起的狀態,此效果在floating=true時生效 |
實現文章開頭效果的整體代碼如下:
class SliverAppBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverAppBar( pinned: true, expandedHeight: 200.0, flexibleSpace: FlexibleSpaceBar( title: Text('復仇者聯盟'), background: Image.network( 'http://img.haote.com/upload/20180918/2018091815372344164.jpg', fit: BoxFit.fitHeight, ), ), ), SliverFixedExtentList( itemExtent: 80.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Card( child: Container( alignment: Alignment.center, color: Colors.primaries[(index % 18)], child: Text(''), ), ); }, ), ), ], ); } }
如果此文章對您有所幫助,歡迎掃碼關注訂閱號,您的點贊、轉發、評論、打賞是我繼續分享的最大動力。