Files
fcs/lib/widget/img_file.dart

155 lines
4.9 KiB
Dart
Raw Normal View History

2020-05-29 07:45:27 +06:30
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fcs/widget/show_img.dart';
typedef OnFile = void Function(File);
class ImageFile extends StatefulWidget {
final String title;
final OnFile onFile;
final bool enabled;
final String initialImgUrl;
final ImageSource imageSource;
const ImageFile(
{Key key,
this.title,
this.onFile,
this.enabled = true,
this.initialImgUrl,
this.imageSource = ImageSource.gallery})
: super(key: key);
@override
_ImageFileState createState() => _ImageFileState();
}
class _ImageFileState extends State<ImageFile> {
String url;
File file;
@override
void initState() {
super.initState();
this.url = widget.initialImgUrl == null || widget.initialImgUrl == ""
? null
: widget.initialImgUrl;
}
@override
Widget build(BuildContext context) {
return Container(
height: 30,
child: this.file == null && this.url == null
? IconButton(
padding: const EdgeInsets.all(3.0),
icon: Icon(Icons.attach_file),
onPressed: () async {
if (!widget.enabled) return;
bool camera = false, gallery = false;
await _dialog(
context, () => camera = true, () => gallery = true);
if (camera || gallery) {
var selectedFile = await ImagePicker.pickImage(
source: camera ? ImageSource.camera : ImageSource.gallery,
imageQuality: 80,
maxWidth: 1000);
if (selectedFile != null) {
setState(() {
this.file = selectedFile;
});
if (widget.onFile != null) {
widget.onFile(selectedFile);
}
}
}
},
)
: Padding(
padding: const EdgeInsets.only(left: 3.0),
child: Chip(
avatar: Icon(Icons.image),
onDeleted: !widget.enabled
? null
: () {
setState(() {
this.file = null;
this.url = null;
if (widget.onFile != null) {
widget.onFile(null);
}
});
},
deleteIcon: Icon(
Icons.close,
),
label: InkWell(
onTap: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ShowImage(
imageFile: file,
url: file == null
? widget.initialImgUrl
: null,
fileName: widget.title)),
)
},
child: Text(widget.title)),
),
),
);
}
Future<void> _dialog(BuildContext context, cameraPress(), photoPress()) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
FontAwesomeIcons.camera,
size: 30,
),
onPressed: () {
Navigator.pop(context);
cameraPress();
}),
Text("Camera")
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(Icons.photo_library, size: 30),
onPressed: () {
Navigator.pop(context);
photoPress();
}),
Text("Gallery")
],
),
],
),
),
),
);
},
);
}
}