Flutter开发:如何将SliverAppBar的leading与actions组件移动到最底部
实现方案
你现在的布局问题是因为FlexibleSpaceBar默认的标题位置在展开状态下位于组件底部,刚好在SliverAppBar自带的leading、actions栏的下方,要反转布局顺序,我们只需要自定义flexibleSpace的布局结构,把标题放到最顶部,图标栏放到标题下方即可,修改后的代码如下:
SliverAppBar( elevation: 2, pinned: true, floating: true, backgroundColor: kLightBGColor, expandedHeight: 150, // 移除原来的leading、actions属性,放到自定义布局中控制顺序 flexibleSpace: FlexibleSpaceBar( background: Container( padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top + 16, left: 16, right: 16, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 先放标题,放在最顶部 const Center( child: Text( 'My Notes', style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.w400, ), ), ), const SizedBox(height: 16), // 再放图标栏,在标题下方 Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Icon(Icons.menu, color: Colors.black), Row( children: const [ Icon(Icons.search, color: Colors.black), SizedBox(width: 8), Icon(Icons.more_vert, color: Colors.black), ], ) ], ), ], ), ), // 折叠状态下显示的标题,和原效果保持一致 title: Text( 'My Notes', style: TextStyle( color: Colors.grey.shade900, fontWeight: FontWeight.w400, ), ), centerTitle: true, titlePadding: const EdgeInsetsDirectional.only( start: 0, bottom: 16, ), ), ),
关键改动说明
- 把原来写在SliverAppBar顶层的leading、actions挪到了flexibleSpace的自定义布局里,你可以自由调整它们和标题的上下排列顺序
- 用
FlexibleSpaceBar.background属性实现展开状态的自定义布局,从上到下依次放标题、图标栏,完全符合你要的反转效果 - 保留了原有的折叠状态标题显示,交互逻辑和之前完全一致,不用修改其他配置
你可以根据自己的设计需求调整padding、间距的数值,匹配你的设计稿效果即可。
内容的提问来源于stack exchange,提问作者Deven Valisten
相关产品推荐
相关产品推荐

