Flutter仿eBay AppBar问题:搜索栏层级与宽度适配异常
问题修复方案
针对你遇到的两个问题,这里给出具体的代码修改和原因说明:
问题1:搜索栏与logo层级颠倒
原代码中SliverAppBar.title是logo,FlexibleSpaceBar.title是搜索栏,而FlexibleSpaceBar的内容在展开状态下会位于SliverAppBar.title的下方区域,导致层级相反。
问题2:搜索栏被挤到图标下方
搜索栏没有设置自适应剩余空间的布局,导致右侧actions区域占据空间后,搜索栏无法收缩宽度,被挤到下方。
修改后的完整代码
Scaffold( body: SafeArea( child: CustomScrollView( slivers: <Widget>[ SliverAppBar( excludeHeaderSemantics: true, backgroundColor: const Color(0xff191919), elevation: 0.0, expandedHeight: width / 3, pinned: true, forceMaterialTransparency: true, // 搜索栏移至SliverAppBar的title,确保顶部层级 title: SizedBox( height: 30, child: Row( children: [ // 使用Expanded让搜索栏占据actions以外的剩余空间 Expanded( child: TextField( textAlignVertical: TextAlignVertical.center, decoration: InputDecoration( hintText: 'Search on eBay', hintStyle: const TextStyle(color: Colors.white, fontSize: 12), filled: true, fillColor: Colors.black, prefixIcon: const Icon( CupertinoIcons.search, size: 20, color: Colors.white, ), suffixIcon: Row( mainAxisSize: MainAxisSize.min, children: [ InkWell( onTap: () {}, child: const Icon( CupertinoIcons.mic, size: 20, color: Colors.white, ), ), const SizedBox(width: 10), InkWell( onTap: () { // Add your onTap code here for the camera icon }, child: const Icon( CupertinoIcons.camera, size: 20, color: Colors.white, ), ), const SizedBox(width: 10), ], ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), borderSide: BorderSide.none, ), ), ), ), ], ), ), actions: [ Padding( padding: const EdgeInsets.all(4), child: Container( padding: const EdgeInsets.all(5), decoration: const BoxDecoration( color: Colors.black, shape: BoxShape.circle, ), child: IconButton( icon: const Icon(CupertinoIcons.cart), color: Colors.white, onPressed: () {}, ), ), ) ], flexibleSpace: FlexibleSpaceBar( expandedTitleScale: 1.5, titlePadding: EdgeInsets.zero, stretchModes: const <StretchMode>[StretchMode.fadeTitle], collapseMode: CollapseMode.pin, centerTitle: true, // logo移至FlexibleSpaceBar,作为展开状态的底部内容 title: Padding( padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8), child: SvgPicture.asset( AppImages.logoImageSvg, width: width / 5, ), ), ), ), ], ), ), );
关键修改点
- 层级调整:将logo移到
FlexibleSpaceBar.title中,搜索栏移到SliverAppBar.title,确保搜索栏始终在logo上方。 - 宽度适配:用
Row+Expanded包裹搜索栏,让它自动填充右侧图标以外的空间,避免被挤压下移。 - 布局优化:开启
FlexibleSpaceBar.centerTitle让logo在展开时居中,更贴近参考效果。
内容的提问来源于stack exchange,提问作者KING NIGHT
相关产品推荐
相关产品推荐

