title.rb
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: DragInAreaExample());
}
}
class DragInAreaExample extends StatefulWidget {
@override
_DragInAreaExampleState createState() => _DragInAreaExampleState();
}
class _DragInAreaExampleState extends State<DragInAreaExample> {
final GlobalKey _targetKey = GlobalKey();
bool _dragStarted = false;
void _checkIfInsideTarget(Offset globalPosition) {
final RenderBox box = _targetKey.currentContext?.findRenderObject() as RenderBox;
final Offset position = box.localToGlobal(Offset.zero);
final Size size = box.size;
final rect = Rect.fromLTWH(position.dx, position.dy, size.width, size.height);
if (rect.contains(globalPosition) && !_dragStarted) {
setState(() {
_dragStarted = true;
});
print('ドラッグ開始(範囲内に入った)');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Listener(
onPointerMove: (event) {
_checkIfInsideTarget(event.position);
},
onPointerUp: (_) {
setState(() => _dragStarted = false);
},
child: Stack(
children: [
Center(
child: Container(
key: _targetKey,
width: 200,
height: 200,
color: _dragStarted ? Colors.green : Colors.blue,
child: Center(child: Text("この範囲にドラッグで入ってみて")),
),
),
],
),
),
);
}
}
title.rb
void _checkIfInsideTarget(Offset globalPosition) {
final RenderBox box = _targetKey.currentContext?.findRenderObject() as RenderBox;
final Offset position = box.localToGlobal(Offset.zero);
final Size size = box.size;
final rect = Rect.fromLTWH(position.dx, position.dy, size.width, size.height);
final isNowInside = rect.contains(globalPosition);
if (isNowInside && !_dragStarted) {
setState(() {
_dragStarted = true;
});
print('枠内に入りました(ドラッグ開始)');
} else if (!isNowInside && _dragStarted) {
setState(() {
_dragStarted = false;
});
print('枠から出ました(キャンセル)');
}
}