如何根据DraggableScrollableSheet的childSize动态切换提示文本与图标
实现方案
你可以通过监听DraggableScrollableController的尺寸变化,动态切换顶部提示文本,具体实现如下:
步骤1:声明状态变量与控制器
首先在当前页面的State类中定义可拖动控制器、当前sheet尺寸变量:
class _YourPageState extends State<YourPage> { // 声明DraggableScrollable专属控制器 late final DraggableScrollableController _sheetController; // 记录当前sheet的尺寸占比,初始值和initialChildSize保持一致 double _currentSheetSize = 0.2; @override void initState() { super.initState(); _sheetController = DraggableScrollableController(); // 添加尺寸变化监听器 _sheetController.addListener(_onSheetSizeChange); } @override void dispose() { // 移除监听器、释放控制器避免内存泄漏 _sheetController.removeListener(_onSheetSizeChange); _sheetController.dispose(); super.dispose(); } // 尺寸变化回调 void _onSheetSizeChange() { if (mounted) { setState(() { _currentSheetSize = _sheetController.size; }); } }
步骤2:绑定控制器并动态渲染提示
给DraggableScrollableSheet绑定控制器,同时对顶部提示区域做条件判断:
Padding( padding: const EdgeInsets.only(right: 8, left: 8), child: DraggableScrollableSheet( controller: _sheetController, // 绑定自定义控制器 initialChildSize: 0.2, minChildSize: 0.2, maxChildSize: 0.55, builder: (context, scrollController) { return SafeArea( child: SingleChildScrollView( controller: scrollController, child: Container( height: 400, decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(30), topLeft: Radius.circular(30.0)), color: Colors.white70, ), child: Column(children: <Widget>[ // 根据当前尺寸动态切换提示文本和图标 RichText( text: TextSpan( style: DefaultTextStyle.of(context).style, children: [ TextSpan( text: _currentSheetSize > 0.35 ? 'Swipe down' : 'Swipe up', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 42, color: Colors.black38)), WidgetSpan( child: SizedBox( width: 40, child: Icon( _currentSheetSize > 0.35 ? Icons.expand_more : Icons.expand_less, size: 42, color: Colors.black38, ), ), ), ], ), ), // 其余原有组件保持不变 SizedBox(height: 10,), Text('data'), SizedBox(height: 10,), Text('data'), SizedBox(height: 10,), Text('data'), SizedBox(height: 10,), Text('data'), SizedBox(height: 10,), Text('data'), ]), ), ), ); }), )
注意事项
- 注意区分两个控制器:
_sheetController是控制sheet整体拖动高度的,builder参数返回的scrollController是控制sheet内部列表滚动的,不要绑定错误 - 控制器返回的
size取值范围严格在你设置的minChildSize和maxChildSize之间,不需要额外做边界处理
内容的提问来源于stack exchange,提问作者user15370388
相关产品推荐
相关产品推荐

