I’m using image picker package. “https://pub.dev/packages/image_picker”
// Get from gallery
void ImgFromGallery() async {
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_proImage = File(pickedFile.path);
List<int> imageBytes = _proImage!.readAsBytesSync();
image = base64Encode(imageBytes);
print("_Proimage:$_proImage");
} else {
print('No image selected.');
}
});
}
It works, but if the user chooses a .gif format from his gallery, I want to run a different function. Can i check extension for selected file? If yes how can i do that? I’m new on Flutter.
File? _file;
String _imagePath = "";
bool imageAccepted;
takeImageFromGallery() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image!.path.endsWith("png")) {
imageAccepted = true;
} else if (image.path.endsWith("jpg")) {
imageAccepted = true;
} else if (image.path.endsWith("jpeg")) {
imageAccepted = true;
} else {
imageAccepted = false;
}
if (imageAccepted) {
if (image != null) {
setState(() {
_imagePath = image.path;
_file = File(_imagePath);
});
}
} else {
SnackBar(content: Text("This file extension is not allowed"));
}
}
You can use Path package like this:
import 'package:path/path.dart' as p;
final path = '/some/path/to/file/file.dart';
final extension = p.extension(path); // '.dart'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With