Flutter Windows应用使用path_provider读取文件失败求助
Flutter Windows应用文件读取问题解决
问题背景
开发Windows平台Flutter应用时,需要每隔几秒读取文件中的值,但无法访问目标文件。由于通过pubspec.yaml配置路径的常规方式会在运行时缓存文件内容,多次调用读取函数也无法获取最新数据,因此未采用该方式。
报错信息
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: "Directory: 'C:\Users\${username_here}\Documents'/data.csv". The asset does not exist or has empty data.
相关代码
获取文件路径的代码:
Future<String> getFilePath(int which) async { Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); String filePath = '${appDocumentsDirectory}/data.csv'; return filePath; } // 忽略未使用的参数
文件读取调用代码:
Future<void> loadFile() async { String filePath = await getFilePath(widget.which); final String csvDataString = await rootBundle.loadString(filePath); List<List<dynamic>> csvTable = const CsvToListConverter().convert(csvDataString); // 尝试获取数据并存入变量,这是第一部分代码 }
排查与解决
通过debugPrint输出确认文件路径正确(C:\Users\${username}\Documents/data.csv),尝试过手动指定路径、转换路径分隔符等方法均无效,最终通过Stack Overflow的解决方案解决了问题。
内容的提问来源于stack exchange,提问作者Abdulkadir Aminu
相关产品推荐
相关产品推荐

