【问题标题】:How to create and Download a Text file in Flutter Mobile如何在 Flutter Mobile 中创建和下载文本文件
【发布时间】:2022-11-16 10:02:50
【问题描述】:

我想创建一个包含一些文本的文本文件,并在用户单击“下载”按钮时下载它。如果用户再次点击同一个下载按钮,它应该创建一个新的文本文件,而不是重写或更新现有文件,因为文本会定期更改。任何建议,将不胜感激。

/// Snippet when user clicks on download second-time 
final permission = Permission.storage;
final status = await permission.status;
debugPrint('>>>Status $status'); /// here it is coming as PermissionStatus.granted
if (status != PermissionStatus.granted) {
  await permission.request();
  if(await permission.status.isGranted){
    directory = Directory('/storage/emulated/0/Download');
    ///perform other stuff to download file
  } else {
   await permission.request();
  }
  debugPrint('>>> ${await permission.status}');
}
directory = Directory('/storage/emulated/0/Download'); 


我确保设置了存储权限。收到此错误

FileSystemException:无法打开文件,路径 = '/storage/emulated/0/Download/codes.txt'(操作系统错误:权限被拒绝,errno = 13)

【问题讨论】:

  • 这是解决方案,请检查它stackoverflow.com/a/59507164/10804348你需要每次设置不同的文件名,这样它就不能覆盖到以前的文件
  • 谢谢@VishalParmar,我已经尝试过了,但它没有按预期工作。
  • 好的,但是你能告诉我你在使用该代码时遇到的问题是什么吗?
  • 当我调用 ${path}.writeAsString('text') 时,有时即使设置了各自的权限也不会下载。此外,如果用户第二次下载,则更新现有文件但不创建新文件。 @VishalParmar
  • 你能在这里展示你到目前为止所做的代码吗

标签: flutter dart dio


【解决方案1】:

如果您不介意重定向到浏览器进行下载,那么您可以使用 url_launcher 包,link

你必须启动你的下载 url,这就是所有的下载部分将由浏览器处理。

//this is download link (you can use your servers path also, here i am using simple drive link)
const String _url = 'https://drive.google.com/uc?export=download&id=1NAEOjqssiQ8f0ATO8kG7At7UDa3sbOg2';

//then to download call this function below 
void _launchURL() async {
  if (!await launch(_url)) throw 'Could not launch $_url';
}

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 2022-01-07
    • 1970-01-01
    • 2013-04-21
    • 2020-09-07
    • 2020-01-16
    • 2020-04-27
    • 1970-01-01
    • 2012-03-01
    相关资源
    最近更新 更多