gpt4 book ai didi

悬停时的 Flutter DragTarget

转载 作者:IT王子 更新时间:2023-10-29 06:54:12 27 4
gpt4 key购买 nike

在探索 Flutter 的 DragTarget 类时,如果您愿意的话,我找不到任何 Hook 到“悬停事件”的机制。这是一个例子:

 class DropZone extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container(
height: 40,
color: Colors.green,
child: DragTarget(
builder: (context, List<int> candidateData, rejectedData) {
print("dragged");
return new Container(color: Colors.red,);
},
onWillAccept: (data) {
return true;
},),
);
}
}

我想在 Draggable 对象悬停但尚未放下时更改容器的颜色。在这种情况下,构建器方法仅在初始渲染期间和 Draggable 离开目标时执行。我怀疑我必须在 onWillAccept 方法中做一些事情但不确定是什么。有人有解决方案吗?

最佳答案

这是我认为您正在寻找的代码

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: App(),
),
);
}
}

class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}

class _AppState extends State<App> {
Color caughtColor = Colors.grey;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
DragBox(Offset(0.0, 0.0), Colors.green),
Positioned(
left: 100,
bottom: 0.0,
child: DragTarget(onAccept: (Color color) {
caughtColor = color;
}, builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
width: 200,
height: 200,
color: accepted.isEmpty ? caughtColor : Colors.grey.shade200,
);
}))
],
);
}
}

class DragBox extends StatefulWidget {
final Offset initPos;
final Color itemColor;

DragBox(this.initPos, this.itemColor);
@override
_DragBoxState createState() => _DragBoxState();
}

class _DragBoxState extends State<DragBox> {
Offset position = Offset(0.0, 0.0);

@override
void initState() {
super.initState();
position = widget.initPos;
}

@override
Widget build(BuildContext context) {
return Positioned(
left: position.dx,
top: position.dy,
child: Draggable(
data: widget.itemColor,
child: Container(
width: 100,
height: 100,
color: widget.itemColor,
),
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
width: 120,
height: 120,
color: widget.itemColor.withOpacity(0.5),
),
),
);
}
}

关于悬停时的 Flutter DragTarget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com