You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过点击按钮展开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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:30:04