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
相关产品推荐
相关产品推荐

