2

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.

Enes UTKU
  • 21
  • 5
  • Does [this](https://stackoverflow.com/questions/62358216/how-to-get-the-file-extension-from-a-string-path) help you? – Peter Koltai Jan 23 '22 at 12:26

2 Answers2

2
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"));
  }
}
1

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'
Saeed Ghasemi
  • 141
  • 1
  • 10