在Scaffold的底部添加一个包裹appBar的SafeArea,然后使用AnimatedBuilder监测AppBar的折叠状态,并相应地更新AppBar的标题。
示例代码如下:
Scaffold(
body: SafeArea(
bottom: false,
child: CustomScrollView(
slivers: [
SliverAppBar(
title: AnimatedBuilder(
animation: _scrollAnimation,
builder: (context, child) {
return _scrollAnimation.value > 0
? Text('My AppBar Title')
: SizedBox.shrink();
},
),
expandedHeight: 200,
flexibleSpace: FlexibleSpaceBar(
background: Image.asset(
'assets/images/header_image.jpg',
fit: BoxFit.cover,
),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return ListTile(
title: Text('List item $index'),
);
},
childCount: 30,
),
),
],
),
),
);
在这个示例中,AnimatedBuilder的builder回调函数根据滚动状态返回一个有标题或者无标题的Text或者SizedBox.shrink()。在这个例子中,滚动的动画值被保存在_scrollAnimation变量中,我们使用这个变量来更新AppBar的标题。我们将此AppBar作为SliverAppBar添加到CustomScrollView的slivers中。最后,我们使用SafeArea在底部包裹整个AppBar,以避免底部被屏幕覆盖。
下一篇:Appbar不会出现