Flutter SliverAppBar背景透明滚动内容穿透问题求助
解决方案
问题出在CustomScrollView中所有sliver处于同一滚动层级,透明的SliverAppBar无法遮挡后续滚动的内容。改用NestedScrollView分离header和内容区域即可解决:
Scaffold( body: Stack( children: <Widget>[ // Screen's Background Color Positioned.fill( child: Container( decoration: BoxDecoration( gradient: RadialGradient( colors: [Colors.black45, Colors.grey.shade800], ), ), ), ), SafeArea( child: NestedScrollView( physics: BouncingScrollPhysics(), // 将SliverAppBar放在header区域 headerSliverBuilder: (context, innerBoxIsScrolled) { return [ SliverAppBar( pinned: true, elevation: 0.0, expandedHeight: 100, backgroundColor: Colors.transparent, flexibleSpace: FlexibleSpaceBar( collapseMode: CollapseMode.pin, title: const Text( 'London', style: TextStyle(color: Colors.white), ), titlePadding: EdgeInsets.all(10.0), ), ), ]; }, // 内容放在body的CustomScrollView中 body: CustomScrollView( slivers: [ SliverPadding(padding: EdgeInsets.all(50)), SliverToBoxAdapter( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Text( '35°', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 40, color: Colors.white, ), ), Text( 'sunny', style: TextStyle( fontSize: 20, color: Colors.white, ), ), ], ), SizedBox(height: 5), Text( 'Mon 40° / 26°', style: TextStyle(color: Colors.white, fontSize: 20), ), ], ), ), ), // Hourly Forecast UI SliverToBoxAdapter(child: HourlyForecastUI()), // Daily Forecast UI SliverToBoxAdapter(child: DailyForecastUI()), // Current Weather Details SliverGrid( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), delegate: SliverChildBuilderDelegate((context, index) { final detailsItem = _currentWeatherDetailsList[index]; return CurrentWeatherDetailsListItem( detailsItem: detailsItem, ); }, childCount: _currentWeatherDetailsList.length), ), ], ), ), ), ], ), );
原理说明
NestedScrollView将header和内容区域分离:
headerSliverBuilder返回的SliverAppBar固定在顶部,属于独立的滚动层级body中的CustomScrollView内容会从header下方开始滚动,不会进入header的区域- 保持
SliverAppBar透明,依然能显示底层的屏幕渐变背景,同时内容不会穿透到AppBar后方
内容的提问来源于stack exchange,提问作者Abdullah Hameed
相关产品推荐
相关产品推荐

