LoginSignup
1
2

More than 3 years have passed since last update.

[Flutter]画像をドラッグすることでカウンターを動かす

Last updated at Posted at 2020-05-17

はじめに

Draggable widgetを使って画像をドラッグできるようにし、さらに指定の領域と重なったときに関数を実行する方法を示します。

今回は初期で作られるカウンターアプリを改変して、ピーターパン症候群のおじさんがリュウグウノツカイと重なるとカウンターが1増えるアプリを作りました。
画面収録 2020-05-18 2.06.46.mov.gif

実装

①ピーターパン症候群のおじさんの画像をDraggableで囲む
②リュウグウノツカイの画像をDraggableTargetで囲む
③重なったときにカウンターを動かす関数をonWillAccept内に記載する

// ①
Draggable(
  child: Image.network(
    // 移動させる画像
    'https://3.bp.blogspot.com/-QxAapI2H1Pk/VhSAsJpLPhI/AAAAAAAAzG0/80qjXfZlomk/s800/peterpan_syndrome.png',
    width: 200,
    height: 200,
  ),
  feedback: Image.network(
    // ドラッグ中の画像
    'https://3.bp.blogspot.com/-QxAapI2H1Pk/VhSAsJpLPhI/AAAAAAAAzG0/80qjXfZlomk/s800/peterpan_syndrome.png',
    width: 220,
    height: 220,
  ),
  childWhenDragging: Opacity(
    // 移動させた元の場所に表示する画像
    opacity: 0.0, // 完全に透明にする
    child: Image.network(
      'https://3.bp.blogspot.com/-QxAapI2H1Pk/VhSAsJpLPhI/AAAAAAAAzG0/80qjXfZlomk/s800/peterpan_syndrome.png',
      width: 200,
      height: 200,
    ),
  ),
  data: 'data',
),
// ②
DragTarget(
  // ドラッグ先の領域
  builder: (context, accepted, rejected) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: _willAccepted ? Colors.orange : Colors.transparent,
          width: _willAccepted ? 1 : 1,
        ),
      ),
      width: 600,
      height: 300,
      child: Center(
        child: Image.network(
'https://4.bp.blogspot.com/-6Sr0RZ5rlAQ/UYh8w3M6Z_I/AAAAAAAARRY/_c7ewyEIZYY/s400/shinkai_ryugunotsukai.png'),
      ),
    );
  },
  // ③
  onWillAccept: (data) {
    // 領域と重複したときの処理
    _incrementCounter();
    _willAccepted = true;
    return true;
  },
  onLeave: (data) {
    // 領域から離れたときの処理
    _willAccepted = false;
  },
),

ドロップしたときの処理など、まだまだ他にもできることはあります。ぜひ下記を参考にしてみてください。
公式ドキュメント
【Flutter】ドラッグ&ドロップの実装

参考

https://api.flutter.dev/flutter/widgets/Draggable-class.html
https://qiita.com/umechanhika/items/2f572f7b58f0316b4faf

1
2
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
1
2