Created
December 24, 2019 12:51
-
-
Save mosheduminer/7ed82c531a2ea8c7dd1fa9f42b442f66 to your computer and use it in GitHub Desktop.
Implementation of a drag-and-drop zone for flutter web. Inspired by https://gist.github.com/PlugFox/ffe83a91ce50f9c78a5b1d6674e36d1b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:html'; | |
import 'package:flutter/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
enum _DragState { | |
dragging, | |
notDragging, | |
} | |
class DropZone extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() { | |
return _DropZoneState(); | |
} | |
} | |
class _DropZoneState extends State<StatefulWidget> { | |
StreamSubscription<MouseEvent> _onDragOverSubscription; | |
StreamSubscription<MouseEvent> _onDropSubscription; | |
final StreamController<Point<double>> _pointStreamController = new StreamController<Point<double>>.broadcast(); | |
final StreamController<_DragState> _dragStateStreamController = new StreamController<_DragState>.broadcast(); | |
@override | |
void dispose() { | |
this._onDropSubscription.cancel(); | |
this._onDragOverSubscription.cancel(); | |
this._pointStreamController.close(); | |
this._dragStateStreamController.close(); | |
super.dispose(); | |
} | |
List<File> _files = <File>[]; | |
void _onDrop(MouseEvent value) { | |
value.stopPropagation(); | |
value.preventDefault(); | |
_pointStreamController.sink.add(null); | |
_addFiles(value.dataTransfer.files); | |
} | |
void _addFiles(List<File> newFiles) { | |
this.setState(() { | |
this._files = this._files..addAll(newFiles); | |
/// TODO | |
print(this._files); | |
}); | |
} | |
void _onDragOver(MouseEvent value) { | |
value.stopPropagation(); | |
value.preventDefault(); | |
this._pointStreamController.sink.add(Point<double>(value.layer.x.toDouble(), value.layer.y.toDouble())); | |
this._dragStateStreamController.sink.add(_DragState.dragging); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
this._onDropSubscription = document.body.onDrop.listen(_onDrop); | |
this._onDragOverSubscription = document.body.onDragOver.listen(_onDragOver); | |
} | |
Widget _fileDrop(BuildContext context) { | |
// styling | |
return Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: Container( | |
height: MediaQuery.of(context).size.height - 200, | |
decoration: BoxDecoration( | |
border: Border.all( | |
color: Color.fromRGBO(125, 125, 125, 0.7) | |
) | |
), | |
), | |
); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return _fileDrop(context); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment