如何在含SliverAppBar与SliverList的CustomScrollView中添加FAB?
Absolutely! This is totally feasible, and there are straightforward ways to pull it off while keeping your SliverList's default scrolling behavior fully intact.
The Recommended Approach: Use Scaffold's FloatingActionButton
The easiest and most idiomatic way is to leverage the Scaffold widget's built-in floatingActionButton property. This renders the FAB in an overlay layer above your CustomScrollView, so it stays fixed on the screen no matter how you scroll your slivers. Your SliverAppBar will still collapse/expand as expected, and the SliverList will scroll normally without any interference.
Here's a complete working example:
Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( title: const Text("My Sliver App Bar"), expandedHeight: 200, floating: true, pinned: true, flexibleSpace: FlexibleSpaceBar( background: Image.network( "https://example.com/your-image.jpg", fit: BoxFit.cover, ), ), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) => ListTile( title: Text("List Item $index"), ), childCount: 50, ), ), ], ), floatingActionButton: FloatingActionButton( onPressed: () { // Add your action logic here }, child: const Icon(Icons.add), ), );
Alternative: Use Stack for Custom Positioning
If you need more control over the FAB's exact placement (beyond what Scaffold provides), wrap your CustomScrollView in a Stack and position the FAB with a Positioned widget. This gives you full control over its location, though you’ll need to handle edge insets manually (like avoiding overlaps with system bars or bottom navigation).
Example:
Stack( children: [ CustomScrollView( slivers: [ // Your SliverAppBar and SliverList go here ], ), Positioned( bottom: 20, right: 20, child: FloatingActionButton( onPressed: () { /* Your action here */ }, child: const Icon(Icons.add), ), ), ], );
Key Notes:
- Using
Scaffoldis preferred because it automatically handles accessibility, screen size adjustments, and proper spacing from system UI elements (like bottom navigation bars or safe areas). - Both methods preserve all default behaviors of your SliverList and SliverAppBar—scrolling, collapsing, and all sliver-specific interactions work exactly as they would without the FAB.
内容的提问来源于stack exchange,提问作者Ian Cruz

