drag_and_drop.dart 7.99 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math' as math;

7
import 'package:flutter/material.dart';
8 9

class ExampleDragTarget extends StatefulComponent {
10
  ExampleDragTargetState createState() => new ExampleDragTargetState();
11
}
12

13
class ExampleDragTargetState extends State<ExampleDragTarget> {
Hixie's avatar
Hixie committed
14
  Color _color = Colors.grey[500];
15

Hixie's avatar
Hixie committed
16
  void _handleAccept(Color data) {
17
    setState(() {
Hixie's avatar
Hixie committed
18
      _color = data;
19 20 21
    });
  }

22
  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
23
    return new DragTarget<Color>(
24
      onAccept: _handleAccept,
25
      builder: (BuildContext context, List<Color> data, List<Color> rejectedData) {
26 27 28 29 30 31
        return new Container(
          height: 100.0,
          margin: new EdgeDims.all(10.0),
          decoration: new BoxDecoration(
            border: new Border.all(
              width: 3.0,
32
              color: data.isEmpty ? Colors.white : Colors.blue[500]
33
            ),
Hixie's avatar
Hixie committed
34
            backgroundColor: data.isEmpty ? _color : Colors.grey[200]
35 36 37 38 39 40 41
          )
        );
      }
    );
  }
}

42 43
class Dot extends StatefulComponent {
  Dot({ Key key, this.color, this.size, this.child, this.tappable: false }) : super(key: key);
Hixie's avatar
Hixie committed
44
  final Color color;
45
  final double size;
Hixie's avatar
Hixie committed
46
  final Widget child;
47 48 49 50 51
  final bool tappable;
  DotState createState() => new DotState();
}
class DotState extends State<Dot> {
  int taps = 0;
52
  Widget build(BuildContext context) {
53 54 55 56 57 58 59 60 61 62 63 64
    return new GestureDetector(
      onTap: config.tappable ? () { setState(() { taps += 1; }); } : null,
      child: new Container(
        width: config.size,
        height: config.size,
        decoration: new BoxDecoration(
          backgroundColor: config.color,
          border: new Border.all(color: const Color(0xFF000000), width: taps.toDouble()),
          shape: BoxShape.circle
        ),
        child: config.child
      )
65 66 67 68
    );
  }
}

Hixie's avatar
Hixie committed
69
class ExampleDragSource extends StatelessComponent {
Hixie's avatar
Hixie committed
70 71 72 73 74 75 76 77
  ExampleDragSource({
    Key key,
    this.color,
    this.heavy: false,
    this.under: true,
    this.child
  }) : super(key: key);

Hixie's avatar
Hixie committed
78
  final Color color;
Hixie's avatar
Hixie committed
79 80 81
  final bool heavy;
  final bool under;
  final Widget child;
82

Hixie's avatar
Hixie committed
83 84 85
  static const double kDotSize = 50.0;
  static const double kHeavyMultiplier = 1.5;
  static const double kFingerSize = 50.0;
86

Hixie's avatar
Hixie committed
87
  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
88
    double size = kDotSize;
89
    if (heavy)
Hixie's avatar
Hixie committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
      size *= kHeavyMultiplier;

    Widget contents = new DefaultTextStyle(
      style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center),
      child: new Dot(
        color: color,
        size: size,
        child: new Center(child: child)
      )
    );

    Widget feedback = new Opacity(
      opacity: 0.75,
      child: contents
    );

    Offset feedbackOffset;
    DragAnchor anchor;
    if (!under) {
      feedback = new Transform(
        transform: new Matrix4.identity()
                     ..translate(-size / 2.0, -(size / 2.0 + kFingerSize)),
        child: feedback
      );
      feedbackOffset = const Offset(0.0, -kFingerSize);
      anchor = DragAnchor.pointer;
    } else {
      feedbackOffset = Offset.zero;
      anchor = DragAnchor.child;
    }

121
    if (heavy) {
Hixie's avatar
Hixie committed
122
      return new LongPressDraggable<Color>(
123 124 125 126 127 128 129
        data: color,
        child: contents,
        feedback: feedback,
        feedbackOffset: feedbackOffset,
        dragAnchor: anchor
      );
    } else {
Hixie's avatar
Hixie committed
130
      return new Draggable<Color>(
131 132 133 134 135 136 137
        data: color,
        child: contents,
        feedback: feedback,
        feedbackOffset: feedbackOffset,
        dragAnchor: anchor
      );
    }
Hixie's avatar
Hixie committed
138 139 140
  }
}

141 142 143 144 145 146 147 148 149 150 151 152
class DashOutlineCirclePainter extends CustomPainter {
  const DashOutlineCirclePainter();

  static const int segments = 17;
  static const double deltaTheta = math.PI * 2 / segments; // radians
  static const double segmentArc = deltaTheta / 2.0; // radians
  static const double startOffset = 1.0; // radians

  void paint(Canvas canvas, Size size) {
    final double radius = size.shortestSide / 2.0;
    final Paint paint = new Paint()
      ..color = const Color(0xFF000000)
153
      ..style = PaintingStyle.stroke
154 155 156 157 158 159 160 161 162 163 164 165 166
      ..strokeWidth = radius / 10.0;
    final Path path = new Path();
    final Rect box = Point.origin & size;
    for (double theta = 0.0; theta < math.PI * 2.0; theta += deltaTheta)
      path.addArc(box, theta + startOffset, segmentArc);
    canvas.drawPath(path, paint);
  }

  bool shouldRepaint(DashOutlineCirclePainter oldPainter) => false;
}

class MovableBall extends StatelessComponent {
  MovableBall(this.position, this.ballPosition, this.callback);
167

168 169 170
  final int position;
  final int ballPosition;
  final ValueChanged<int> callback;
171 172

  static final GlobalKey kBallKey = new GlobalKey();
173
  static const double kBallSize = 50.0;
174

175 176 177 178 179 180 181
  Widget build(BuildContext context) {
    Widget ball = new DefaultTextStyle(
      style: Theme.of(context).text.body1.copyWith(
        textAlign: TextAlign.center,
        color: Colors.white
      ),
      child: new Dot(
182
        key: kBallKey,
183 184
        color: Colors.blue[700],
        size: kBallSize,
185
        tappable: true,
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        child: new Center(child: new Text('BALL'))
      )
    );
    Widget dashedBall = new Container(
      width: kBallSize,
      height: kBallSize,
      child: new CustomPaint(
        painter: const DashOutlineCirclePainter()
      )
    );
    if (position == ballPosition) {
      return new Draggable<bool>(
        data: true,
        child: ball,
        childWhenDragging: dashedBall,
        feedback: ball,
        maxSimultaneousDrags: 1
      );
    } else {
      return new DragTarget<bool>(
        onAccept: (bool data) { callback(position); },
        builder: (BuildContext context, List<bool> accepted, List<bool> rejected) {
          return dashedBall;
        }
      );
    }
  }
}

class DragAndDropApp extends StatefulComponent {
  DragAndDropAppState createState() => new DragAndDropAppState();
}

class DragAndDropAppState extends State<DragAndDropApp> {
  int position = 1;
  void moveBall(int newPosition) {
    setState(() { position = newPosition; });
  }
224
  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
225
    return new Scaffold(
Adam Barth's avatar
Adam Barth committed
226
      toolBar: new ToolBar(
Hixie's avatar
Hixie committed
227
        center: new Text('Drag and Drop Flutter Demo')
228
      ),
229 230
      body: new Column(
        children: <Widget>[
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
          new Flexible(
            child: new Row(
              children: <Widget>[
                new ExampleDragSource(
                  color: Colors.yellow[300],
                  under: true,
                  heavy: false,
                  child: new Text('under')
                ),
                new ExampleDragSource(
                  color: Colors.green[300],
                  under: false,
                  heavy: true,
                  child: new Text('long-press above')
                ),
                new ExampleDragSource(
                  color: Colors.indigo[300],
                  under: false,
                  heavy: false,
                  child: new Text('above')
                ),
              ],
              alignItems: FlexAlignItems.center,
              justifyContent: FlexJustifyContent.spaceAround
            )
          ),
257 258 259 260 261 262 263 264 265 266
          new Flexible(
            child: new Row(
              children: <Widget>[
                new Flexible(child: new ExampleDragTarget()),
                new Flexible(child: new ExampleDragTarget()),
                new Flexible(child: new ExampleDragTarget()),
                new Flexible(child: new ExampleDragTarget()),
              ]
            )
          ),
267 268 269 270 271 272 273 274 275 276
          new Flexible(
            child: new Row(
              children: <Widget>[
                new MovableBall(1, position, moveBall),
                new MovableBall(2, position, moveBall),
                new MovableBall(3, position, moveBall),
              ],
              justifyContent: FlexJustifyContent.spaceAround
            )
          ),
277 278
        ]
      )
279 280 281 282 283
    );
  }
}

void main() {
Adam Barth's avatar
Adam Barth committed
284
  runApp(new MaterialApp(
Hixie's avatar
Hixie committed
285
    title: 'Drag and Drop Flutter Demo',
Hixie's avatar
Hixie committed
286
    routes: <String, RouteBuilder>{
Ian Hickson's avatar
Ian Hickson committed
287
     '/': (RouteArguments args) => new DragAndDropApp()
Hixie's avatar
Hixie committed
288 289
    }
  ));
290
}