当前位置: 首页 > news >正文

在Flutter上如何实现按钮的拖拽效果

1、使用 Draggable 和 DragTarget 配合一起使用

Draggable 定义可拖拽对象和拖动时,拖动对象的样子

DragTarget 定义拖拽后接收对象,可拿到Draggable携带的数据

import 'package:flutter/material.dart';class Test extends StatefulWidget {const Test({super.key});@overrideState<Test> createState() => _TestState();
}class _TestState extends State<Test> {Color curColor = Colors.orange;@overrideWidget build(BuildContext context) {return Column(children: [Draggable<Color>(data: Colors.blue,feedback: Container(width: 50,height: 50,color: Colors.blue,),child: Container(width: 50,height: 50,color: Colors.blue,),),Draggable<Color>(data: Colors.yellow,feedback: Container(width: 50,height: 50,color: Colors.yellow,),child: Container(width: 50,height: 50,color: Colors.yellow,),),Draggable<Color>(data: Colors.red,feedback: Container(width: 50,height: 50,color: Colors.red,),child: Container(width: 50,height: 50,color: Colors.red,),),DragTarget<Color>(onAcceptWithDetails: (DragTargetDetails c) {print(c);setState(() {curColor = c.data as Color;});},builder: (context, _, __) {return Container(width: 50,height: 50,color: curColor,alignment: Alignment.center,child: const Text('拖放到这里'),);},),],);}
}

特点​:

  • 支持拖拽数据传递(通过data参数)。
  • 提供完整的拖拽生命周期回调(如onDragStartedonDragEnd

方式二:利用GestureDetector 的onPanUpdate函数来监听 移动

import 'package:flutter/material.dart';class DraggableButton extends StatefulWidget {const DraggableButton({super.key});@overrideState<DraggableButton> createState() => _DraggableButtonState();
}class _DraggableButtonState extends State<DraggableButton> {Offset _offset = Offset.zero;@overrideWidget build(BuildContext context) {return SizedBox(width: double.infinity,height: 400,child: Stack(children: [Positioned(left: _offset.dx,top: _offset.dy,child: GestureDetector(onPanUpdate: (details) {setState(() {_offset += details.delta; // 更新偏移量});},child: FloatingActionButton(onPressed: () {},child: const Icon(Icons.drag_handle),),),),],),);}
}

第三、使用第三方库

flutter_draggable_gridview | Flutter package

draggable_float_widget | Flutter package

draggable_home | Flutter package

http://www.xdnf.cn/news/427789.html

相关文章:

  • Ceph 集群常用管理命令
  • esp32硬件支持AT指令
  • 什么类型的网站适合用WAF?Web应用防火墙的适用场景解析
  • Python(1) 做一个随机数的游戏
  • MySQL索引底层数据结构与算法
  • Vue 2 和 Vue 3的比较(二、语法差异)
  • Excel的详细使用指南
  • Mac修改hosts文件方法
  • Linux文件编程——标准库函数fopen、fread、fwrite等函数
  • Confusion2(Python反序列化+JWT)
  • MySQL——八、SQL优化
  • 【deekseek】P2P通信路由过程
  • 测试报告--博客系统
  • --openssl-legacy-provider is not allowed in NODE_OPTIONS 报错的处理方式
  • 栈与乘积 / 栈
  • rk3576--- HDMI CEC唤醒
  • TCP核心机制
  • 机器学习第八讲:向量/矩阵 → 数据表格的数学表达,如Excel表格转数字阵列
  • 已情感分析入门学习大模型-初级篇
  • MCP-RAG 服务器:完整设置和使用指南
  • Java 集合与 MyBatis 动态 SQL 实战教程
  • 普通项目与 FreeRTOS 项目的异同
  • 【NLP 72、Prompt、Agent、MCP、function calling】
  • 全景系统监控利器:Glances 使用介绍与实战指南
  • 【数据结构】双向链表
  • 开发与AI融合的Windsurf编辑器
  • 屏幕与触摸调试
  • Retrofit vs Feign: 介绍、对比及示例
  • 关于 javax.validation.constraints的详细说明
  • Visual Studio 项目 .gitignore 文件指南