Flutter中文件扩展名的函数

mklgxw1f  于 2022-12-05  发布在  Flutter
关注(0)|答案(2)|浏览(240)

我正在使用图像拾取器包。“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.');
      }
    });
  }

它的工作,但如果用户选择了一个.gif格式从他的画廊,我想运行一个不同的功能。我可以检查所选文件的扩展名吗?如果是的话,我怎么做?我是新的Flutter。

uinbv5nw

uinbv5nw1#

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

snvhrwxg2#

您可以像这样使用Path包:

import 'package:path/path.dart' as p;

final path = '/some/path/to/file/file.dart';

final extension = p.extension(path); // '.dart'

相关问题