如何通过点击按钮展开Flutter的DraggableScrollableSheet?
解决DraggableScrollableSheet点击"Expand"无法展开的问题
你当前代码的问题在于,调用scrollController.animateTo(0.9)时,这个scrollController是ListView的滚动控制器,负责控制列表内部的滚动,而非控制DraggableScrollableSheet的展开/收起尺寸。要实现点击展开sheet的效果,需要使用专门的DraggableScrollableController。
修复步骤:
- 创建
DraggableScrollableController实例,用于控制sheet的尺寸变化 - 将该控制器绑定到
DraggableScrollableSheet的controller参数上 - 在"Expand"的点击事件中,调用该控制器的
animateTo或snapToPosition方法
修改后的完整代码:
void thingTapped(BuildContext context) { final sheetController = DraggableScrollableController(); double a = 0; showModalBottomSheet( isScrollControlled: true, backgroundColor: Colors.transparent, isDismissible: true, context: context, builder: (context) { return NotificationListener<DraggableScrollableNotification>( onNotification: (DraggableScrollableNotification dsNotification) { a = dsNotification.extent; print("Notification: $a"); return true; }, child: DraggableScrollableSheet( controller: sheetController, // 绑定sheet控制器 maxChildSize: 0.9, minChildSize: 0.15, initialChildSize: 0.2, snap: true, shouldCloseOnMinExtent: true, snapSizes: const <double>[0.2, 0.9], builder: (context, scrollController) => Card( color: Colors.white, child: ListView( controller: scrollController, // 这个还是ListView的滚动控制器,保留不变 children: [ const Text( "This gonna be a cool title", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), const Text( "And this gonna be a cooler sub-title :)", style: TextStyle(fontSize: 16), ), InkWell( onTap: () => sheetController.animateTo( 0.9, curve: Curves.easeIn, duration: const Duration(seconds: 2), ), // 如果你想贴合snap配置,也可以用snapToPosition: // onTap: () => sheetController.snapToPosition(0.9), child: const Text( "Expand", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), ), ], ), ), ), ); }, ); }
补充说明:
DraggableScrollableController是专门为DraggableScrollableSheet设计的控制器,用于控制其extent(即占屏幕的比例)- 因为你设置了
snap: true和snapSizes,使用snapToPosition(0.9)会直接跳到预设的snap位置,动画更贴合你的配置逻辑
内容的提问来源于stack exchange,提问作者Alvaro Dosio
相关产品推荐
相关产品推荐

