Last active
December 29, 2019 03:58
-
-
Save thetrav/9823df5fbcda256cdfeb56a9c44ac2af to your computer and use it in GitHub Desktop.
File input widget
This file contains 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: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