MSIPO技术圈 首页 IT技术 查看内容

【Flutter】文件选择器(file_picker)的用法

2024-03-25

Flutter 没有提供内置的文件选择器,但社区内有人贡献了一个比较完整的解决方案——file_picker

file_picker 的 API 简洁易用,支持全平台(Android / iOS / Mac / Linux / Windows),是我开发桌面应用时的首选。

这边博客简单介绍它的基本用法并提供一个应用实例。

基本用法

选择单个文件

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  File file = File(result.files.single.path!);
} else {
  // User canceled the picker
}

选择多个文件

FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

if (result != null) {
  List<File> files = result.paths.map((path) => File(path!)).toList();
} else {
  // User canceled the picker
}

指定文件后缀

FilePickerResult? result = await FilePicker.platform.pickFiles(
  type: FileType.custom,
  allowedExtensions: ['jpg', 'pdf', 'doc'],
);

选择文件夹

String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

if (selectedDirectory == null) {
  // User canceled the picker
}

读取文件属性

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  PlatformFile file = result.files.first;

  print(file.name);
  print(file.bytes);
  print(file.size);
  print(file.extension);
  print(file.path);
} else {
  // User canceled the picker
}

保存文件至云端

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  Uint8List fileBytes = result.files.first.bytes;
  String fileName = result.files.first.name;
  
  // Upload file
  await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}

应用实例

下图是我用 Flutter 绘制的语法知识图片,我想把它保存成图片,应该如何实现呢?

首先,借助 RepaintBoundary 指定需要绘制的区域:

RepaintBoundary(
  key: _globalKey,
  child: _buildCover(context, _rectangle),
),

然后,通过 globalKey 将该区域内的数据转化为一张图片:

Future<Uint8List?> captureWidget(GlobalKey globalKey) async {
  final boundary =
      globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
  final image = await boundary.toImage(pixelRatio: 3.0);
  final byteData = await image.toByteData(format: ImageByteFormat.png);
  return byteData?.buffer.asUint8List();
}

最后,利用 FilePicker 保存图片数据(类型为 Uint8List):

Future<void> saveImageToFile(Uint8List bytes, String fileName) async {
  // Directory appDocDir = await getApplicationDocumentsDirectory();
  // String appDocPath = appDocDir.path;
  String? outputFile = await FilePicker.platform.saveFile(
    dialogTitle: 'Save to:',
    fileName: fileName,
  );

  if (outputFile != null) {
    File file = File(outputFile);
    file.writeAsBytes(bytes);
  }
}

以上就是 Flutter 文件选择器 FilePicker 的用法,感谢阅读。

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部