Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions by file extension in Flutter

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.

like image 424
Enes UTKU Avatar asked Aug 31 '25 01:08

Enes UTKU


2 Answers

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"));
  }
}
like image 125
Tanya Malhotra Avatar answered Sep 02 '25 19:09

Tanya Malhotra


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'
like image 39
Saeed Ghasemi Avatar answered Sep 02 '25 19:09

Saeed Ghasemi