【问题标题】:From path to File conversion with Flutter使用 Flutter 从路径到文件的转换
【发布时间】:2021-02-03 07:14:54
【问题描述】:

我正在做一个颤振项目。我需要从设备存储中选择一个文件。我可以获取文档的路径,但我需要将其保存为文件或直接将其获取为文件。要创建路径字符串,我使用 flutter_document_picker: 3.0.1

 Future getDocument(int index) async {
    var document = await FlutterDocumentPicker.openDocument();

    setState(() {
      if (document != null) {
        lstDocument[index] = document;
        Navigator.pop(context);
      }
    });
  }

有谁知道如何将文档保存为文件。谢谢解决。

【问题讨论】:

    标签: android android-studio flutter cross-platform


    【解决方案1】:

    您可以使用flutter_absolute_path 将路径转换为 ​​File()。

        import 'package:flutter_absolute_path/flutter_absolute_path.dart';
        Future getDocument(int index) async {
            String documentLocation = await FlutterDocumentPicker.openDocument();
        
            if (documentLocation != null) {
              
              final document =
                  await FlutterAbsolutePath.getAbsolutePath(documentLocation);
              File tempFile = File(document);
              setState(() {
                if (tempFile != null) {
                  lstDocument[index] = tempFile;
                  Navigator.pop(context);
                }
              });
            }
          }
    

    【讨论】:

      【解决方案2】:

      您可以使用path_provider 包将文件保存到您的手机。

      import 'package:path_provider/path_provider.dart';
      
      Future getDocument(int index) async {
        var document = await FlutterDocumentPicker.openDocument();
      
        setState(() {
          if (document != null) {
            lstDocument[index] = document;
      
            final String path = await getApplicationDocumentsDirectory().path;
      
            // copy the file to a new path
            final File newImage = await image.copy('$path/image1.png'); // For Image Files
      
            Navigator.pop(context);
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-07
        • 2022-08-22
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 2017-11-22
        • 2014-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多