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

Flutter:如何通过手势实现Widget垂直方向拖拽调整大小

Flutter 实现拖拽顶部/底部调整Widget大小

可以通过GestureDetector监听拖拽手势,结合状态管理动态调整Widget高度,以下是具体实现方案:

核心思路

  • 维护动态高度变量,控制目标Widget的尺寸
  • 在Widget顶部、底部添加可拖拽的"手柄"区域,监听拖拽手势
  • 根据拖拽的垂直偏移量更新高度,同时限制最小/最大高度避免异常

完整代码示例

import 'package:flutter/material.dart';

class ResizableWidget extends StatefulWidget {
  final Widget child;
  final double initialHeight;
  final double minHeight;
  final double maxHeight;

  const ResizableWidget({
    super.key,
    required this.child,
    this.initialHeight = 200,
    this.minHeight = 100,
    this.maxHeight = 400,
  });

  @override
  State<ResizableWidget> createState() => _ResizableWidgetState();
}

class _ResizableWidgetState extends State<ResizableWidget> {
  late double _currentHeight;

  @override
  void initState() {
    super.initState();
    _currentHeight = widget.initialHeight;
  }

  // 处理顶部拖拽逻辑
  void _handleTopDragUpdate(DragUpdateDetails details) {
    setState(() {
      _currentHeight = (_currentHeight - details.delta.dy).clamp(
        widget.minHeight,
        widget.maxHeight,
      );
    });
  }

  // 处理底部拖拽逻辑
  void _handleBottomDragUpdate(DragUpdateDetails details) {
    setState(() {
      _currentHeight = (_currentHeight + details.delta.dy).clamp(
        widget.minHeight,
        widget.maxHeight,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 顶部拖拽手柄
        GestureDetector(
          onPanUpdate: _handleTopDragUpdate,
          child: Container(
            height: 10,
            color: Colors.grey[300],
            child: const Center(
              child: Icon(Icons.drag_indicator, size: 16),
            ),
          ),
        ),
        // 可调整大小的内容区域
        SizedBox(
          height: _currentHeight,
          child: widget.child,
        ),
        // 底部拖拽手柄
        GestureDetector(
          onPanUpdate: _handleBottomDragUpdate,
          child: Container(
            height: 10,
            color: Colors.grey[300],
            child: const Center(
              child: Icon(Icons.drag_indicator, size: 16),
            ),
          ),
        ),
      ],
    );
  }
}

// 使用示例
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(
        child: ResizableWidget(
          child: Card(
            color: Colors.blue[100],
            child: const Center(child: Text("可拖拽调整大小的Widget")),
          ),
        ),
      ),
    ),
  ));
}

代码说明

  • ResizableWidget是可复用组件,支持传入初始高度、最小/最大高度和子Widget
  • 顶部手柄向上拖拽增加高度,向下拖拽减少高度;底部手柄逻辑相反
  • 通过clamp方法限制高度范围,避免超出合理区间

内容的提问来源于stack exchange,提问作者Maria Grigoryan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:20:21