【问题标题】:Create Folder When Installing Application安装应用程序时创建文件夹
【发布时间】:2018-09-19 15:38:35
【问题描述】:

如何在设备存储中创建文件夹来保存文件?

这是下载文件到设备的代码:

import 'package:flutter_downloader/flutter_downloader.dart';

onTap: () async { //ListTile attribute
   Directory appDocDir = await getApplicationDocumentsDirectory();                
   String appDocPath = appDocDir.path;
   final taskId = await FlutterDownloader.enqueue(
     url: 'http://myapp/${attach[index]}',
     savedDir: '/sdcard/myapp',
     showNotification: true, // show download progress in status bar (for Android)
     clickToOpenDownloadedFile: true, // click on notification to open downloaded file (for Android)
   );
},

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您可以在应用启动时创建目录。 在第一个屏幕的 initState() 方法中执行逻辑。

    例如

    createDir() async {
      Directory baseDir = await getExternalStorageDirectory(); //only for Android
      // Directory baseDir = await getApplicationDocumentsDirectory(); //works for both iOS and Android
      String dirToBeCreated = "<your_dir_name>";
      String finalDir = join(baseDir, dirToBeCreated);
      var dir = Directory(finalDir);
      bool dirExists = await dir.exists();
      if(!dirExists){
         dir.create(/*recursive=true*/); //pass recursive as true if directory is recursive
      }
      //Now you can use this directory for saving file, etc.
      //In case you are using external storage, make sure you have storage permissions.
    }
    
    @override
    initState(){
      createDir(); //call your method here
      super.initState();
    }
    

    您需要导入这些库:

    import 'dart:io';
    import 'package:path/path.dart';
    import 'package:path_provider/path_provider.dart';
    

    【讨论】:

    • 存储/仿真/0/Android/data/com.被创建了....我想像whatsapp一样在sdcard中,...
    【解决方案2】:
    //add in pubspec.yaml
    path_provider:
    
    //import this
    import 'dart:io' as io;
    import 'package:path_provider/path_provider.dart';
    
    //create Variable 
    String directory = (await getApplicationDocumentsDirectory()).path;
    
    //initstate to create directory at launch time
    @override
      void initState() {
        // TODO: implement initState
        super.initState();
        createFolder();
      }
    
    //call this method from init state to create folder if the folder is not exists
    void createFolder() async {
        if (await io.Directory(directory + "/yourDirectoryName").exists() != true) {
          print("Directory not exist");
          new io.Directory(directory + "/your DirectoryName").createSync(recursive: true);
    //do your work
        } else {
          print("Directoryexist");
    
    //do your work
        }
      }
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
    【解决方案3】:

    据我所见,您没有在任何地方使用appDocDirappDocPath,因为您将文件保存在/sdcard/myapp 中。

    请检查您是否要求并授予存储权限,并且无法像您一样将文件存储在 sdcard 中。要么使用预定义的目录,如(文档、图片等),要么使用以storage/emulated/0 开头的设备根目录

    【讨论】:

    • 是否每个 android 设备根目录都以“storage/emulated/0”开头,无论它运行的是哪个 android API 级别?
    【解决方案4】:

    这是在用户内部存储中创建文件夹的示例代码希望对您有所帮助

    import 'dart:io' as Io;
    
    
    
    Future _downloadImage() async {
    try {
        // request runtime permission
        final permissionHandler = PermissionHandler();
        final status = await permissionHandler
            .checkPermissionStatus(PermissionGroup.storage);
        if (status != PermissionStatus.granted) {
          final requestRes = await permissionHandler
              .requestPermissions([PermissionGroup.storage]);
          if (requestRes[PermissionGroup.storage] != PermissionStatus.granted) {
            _showSnackBar('Permission denined. Go to setting to granted!');
            return _done();
          }
        }
      }
      var testdir =
      await new Io.Directory('/storage/emulated/0/MyApp').create(recursive: true);
      final filePath =
          path.join(testdir.path, Filename + '.png');
      print(filePath);
      final file = File(filePath);
      if (file.existsSync()) {
        file.deleteSync();
      }
     //save image to storage
      var request = await HttpClient().getUrl(Uri.parse(imageUrl));
      var response = await request.close();
      final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
      final saveFileResult =
          saveImage({'filePath': filePath, 'bytes': bytes});
     _showSnackBar(
        saveFileResult
            ? 'Image downloaded successfully'
            : 'Failed to download image',
      );
    } on PlatformException catch (e) {
      _showSnackBar(e.message);
    } catch (e, s) {
      _showSnackBar('An error occurred');
      debugPrint('Download image: $e, $s');
    }
    return _done();
     }
    

    【讨论】:

      【解决方案5】:

      首先你需要导入

      1) 导入'dart:io';

      其次,您需要在 async/await 函数中为指定路径创建目录

      2) 例如: await new Directory('/storage/emulated/0/yourFolder').create(recursive: true);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 2015-05-12
        • 1970-01-01
        相关资源
        最近更新 更多