颤抖如何创建文件夹以将文件存储在内部存储中

时间:2019-03-08 12:32:46

标签: dart flutter

我遇到了一个问题,我必须从网络下载pdf或图像并将其存储在本地存储中。我正在尝试使用GetApplicationDocumentDirectory成功安装文件但未显示在设备文件夹中的路径提供程序插件。如何创建目录并存储对用户可见的图像pdf等文件。我怎么能做到这一点。

谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以通过创建文件夹来写入设备外部存储,如下面的示例代码所示

希望有帮助

class PDFDownloader extends StatefulWidget {
  final String extension;
  final String url;
  final String fileName;

  PDFDownloader(this.url, this.fileName,[this.extension='pdf']);

  @override
  _DownloadAppState createState() => new _DownloadAppState();
}

class _DownloadAppState extends State<PDFDownloader> {

  bool downloading = false;
  String _message;
  var progressString = "";
  Future<Directory> _externalDocumentsDirectory;

  @override
  void initState() {
    //downloadFile();
    checkPer();
//    _bannerAd = createBannerAd()..load();

    super.initState();
  }

  void checkPer() async {
    await new Future.delayed(new Duration(seconds: 1));
    bool checkResult = await SimplePermissions.checkPermission(
        Permission.WriteExternalStorage);
    if (!checkResult) {
      var status = await SimplePermissions.requestPermission(
          Permission.WriteExternalStorage);
      //print("permission request result is " + resReq.toString());
      if (status == PermissionStatus.authorized) {
        await downloadFile();
      }
    } else {
      await downloadFile();
    }
  }

  @override
  Widget build(BuildContext context) {
    var scaffold= Scaffold(
      appBar: AppBar(
        title: Text("Download"),
      ),
      body: Center(
        child: downloading
            ? Container(
          height: 120.0,
          width: 200.0,
          child: Card(
            color: Colors.black,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CircularProgressIndicator(),
                SizedBox(
                  height: 20.0,
                ),
                Text(
                  "Downloading File: $progressString",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                )
              ],
            ),
          ),
        )
            : Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_message ?? 'Please wait!!'),
            SizedBox(
              height: 10.0,
            ),
            new RaisedButton(
              textColor: Colors.white,
              color: Colors.blueAccent,
              shape: new RoundedRectangleBorder(
                  borderRadius: new BorderRadius.circular(10.0)),
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('Close'),
            )
          ],
        ),
      ),
    );
    return WillPopScope(
      onWillPop: _onWillPop,
      child: scaffold,
    );
  }

  Future<bool> _onWillPop() {
    return new Future.value(!downloading);
  }

  Future<void> downloadFile() async {
    var dio = new Dio();
    var dir = await getExternalStorageDirectory();
    var knockDir =
    await new Directory('${dir.path}/iLearn').create(recursive: true);
    print(widget.url);
    await dio.download(widget.url, '${knockDir.path}/${widget.fileName}.${widget.extension}',
        onProgress: (rec, total) {
          //print("Rec: $rec , Total: $total");

          if (mounted) {
            setState(() {
              downloading = true;
              progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
            });
          }
        });
    if (mounted) {
      setState(() {
        downloading = false;
        progressString = "Completed";
        _message = "File is downloaded to your SD card 'iLearn' folder!";
      });
    }
    print("Download completed");
  }
}

答案 1 :(得分:0)

要在内部存储中创建应用程序目录,请使用以下代码段:

        Directory directory = await getExternalStorageDirectory();
        String fileName =
            "xyz.pdf";
        String newPath = "";
        print(directory);
        List<String> paths = directory.path.split("/");
        for (int x = 1; x < paths.length; x++) {
          String folder = paths[x];
          if (folder != "Android") {
            newPath += "/" + folder;
          } else {
            break;
          }
        }
        newPath = newPath + "/YourAppName";
        directory = Directory(newPath);

        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
        if (await directory.exists()) {
          final File file = File(directory.path + "/$fileName");
          // your logic for saving the file.
        }

有关详细说明,请查看 Retroportal Studio 的这篇 Medium 文章: https://retroportalstudio.medium.com/saving-files-to-application-folder-and-gallery-in-flutter-e9be2ebee92a