-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimage_picker_utils.dart
64 lines (58 loc) · 1.61 KB
/
image_picker_utils.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' as PathProvider;
class ImagePickerUtils {
static ImagePicker _picker = new ImagePicker();
static Future<Directory> _getDirectory() async {
return await PathProvider.getApplicationSupportDirectory();
}
static Future<File?> _getImageFile() async {
var directory = await _getDirectory();
if (!directory.existsSync()) {
return null;
}
try {
var list = directory.listSync();
if (list.isEmpty) {
return null;
} else {
return File(list.first.path);
}
} catch (e) {
print(e);
return null;
}
}
static Future<Image?> getImage(context) async {
var size = MediaQuery.of(context).size;
var imageFile = await _getImageFile();
var exists = await imageFile?.exists() ?? false;
if (exists && imageFile != null) {
return Image.file(
imageFile,
fit: BoxFit.cover,
width: size.width,
height: size.height,
);
} else {
return null;
}
}
static void clearImage() => _getDirectory().then((value) {
value.listSync().forEach((element) {
element.delete();
});
});
static Future<bool> browseForImage() async {
var image = await _picker.pickImage(source: ImageSource.gallery);
// user cancelled
if (image == null) {
return false;
}
Directory directory = await _getDirectory();
String path = directory.path + '/' + image.name;
image.saveTo(path);
return true;
}
}