0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

備忘録

Posted at
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('枠から出ました(キャンセル)');
  }
}


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?