Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implementation of a drag-and-drop zone for flutter web. Inspired by https://gist.github.com/PlugFox/ffe83a91ce50f9c78a5b1d6674e36d1b
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