From 6f129290573a3cd8be8f343b4f00bbeee7cb7b22 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Sun, 24 May 2020 22:50:49 +1000 Subject: [PATCH] Add image selection field which allows picking from gallery or taking a new photo with camera --- lib/widget/fields.dart | 86 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/lib/widget/fields.dart b/lib/widget/fields.dart index 452afb50..80718bc5 100644 --- a/lib/widget/fields.dart +++ b/lib/widget/fields.dart @@ -1,5 +1,89 @@ import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:image_picker/image_picker.dart'; + +import 'dart:async'; +import 'dart:io'; + +// TODO - Perhaps refactor all this using flutter_form_builder - https://pub.dev/packages/flutter_form_builder + + +/* + * Form field for selecting an image file, + * either from the gallery, or from the camera. + */ +class ImagePickerField extends FormField { + + static void _selectFromGallery(FormFieldState field) { + _getImageFromGallery(field); + } + + static void _selectFromCamera(FormFieldState field) { + _getImageFromCamera(field); + } + + static Future _getImageFromGallery(FormFieldState field) async { + + File image; + + await ImagePicker.pickImage(source: ImageSource.gallery).then((File img) { + image = img; + }); + + field.didChange(image); + } + + static Future _getImageFromCamera(FormFieldState field) async { + File image; + + await ImagePicker.pickImage(source: ImageSource.camera).then((File img) { + image = img; + }); + + field.didChange(image); + } + + ImagePickerField({String label = "Attach Image", Function onSaved, bool required = false}) : + super( + onSaved: onSaved, + validator: (File img) { + if (required && (img == null)) { + return "Required"; + } + + return null; + }, + builder: (FormFieldState state) { + return InputDecorator( + decoration: InputDecoration( + errorText: state.errorText, + labelText: required ? label + "*" : label, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + FlatButton( + child: Text("Select Image"), + onPressed: () { + _selectFromGallery(state); + }, + ), + FlatButton( + child: Text("Take Picture"), + onPressed: () { + _selectFromCamera(state); + }, + ) + ], + ), + ); + return ListTile( + title: Text("Select Image"), + ); + } + ); +} class CheckBoxField extends FormField { @@ -25,7 +109,7 @@ class StringField extends TextFormField { StringField({String label, String hint, String initial, Function onSaved, Function validator, bool allowEmpty = false, bool isEnabled = true}) : super( decoration: InputDecoration( - labelText: label, + labelText: allowEmpty ? label : label + "*", hintText: hint ), initialValue: initial,