Skip to content

Instantly share code, notes, and snippets.

@thetrav
Last active December 29, 2019 03:58
Show Gist options
  • Save thetrav/9823df5fbcda256cdfeb56a9c44ac2af to your computer and use it in GitHub Desktop.
Save thetrav/9823df5fbcda256cdfeb56a9c44ac2af to your computer and use it in GitHub Desktop.
File input widget
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:growdata_shared_web/component/gd_red_text.dart';
class GdFileInput extends StatefulWidget {
final void Function(String, List<int>) fileSelected;
final List<String> extensions;
GdFileInput(this.fileSelected, {this.extensions});
@override
State<StatefulWidget> createState() => _GdFileInput();
}
class _GdFileInput extends State<GdFileInput> {
String selectedFileName;
String error;
bool loading;
bool validName(String name) => widget.extensions == null || widget.extensions.firstWhere(
(ext) => name.endsWith(ext),
orElse: () => null
) != null;
void _startFilePicker() {
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((e) {
final files = uploadInput?.files;
if (files.length == 1) {
final file = files[0];
String name = file?.name;
if(validName(name)) {
FileReader reader = FileReader();
setState(() {
selectedFileName = null;
error = null;
loading = true;
});
reader.onLoadEnd.listen((e) {
setState(() {
selectedFileName = name;
error = null;
loading = false;
});
final result = reader.result;
widget.fileSelected(name, result as List<int>);
});
reader.onError.listen((e) {
setState(() {
selectedFileName = null;
error = "Error reading file: $e";
});
});
reader.readAsArrayBuffer(file);
} else {
setState(() {
selectedFileName = null;
error = "File must end with ${widget.extensions.join(" or ")}";
print("error set to $error");
});
}
}
});
}
@override
Widget build(BuildContext context) {
final selected = selectedFileName != null;
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RaisedButton.icon(
label: Text("Select File"),
icon: Icon(selected ? Icons.check_circle_outline : Icons.error_outline ),
color: selected ? Colors.green : Colors.red.shade700,
onPressed: _startFilePicker
),
selectedFileName != null ?
Text(selectedFileName) :
GdRedText(error ?? "")
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment