回到开始,但更接近我需要的解决方案。我有 file_picker ( https://pub.dartlang.org/packages/file_picker ),它有助于使用文件资源管理器选择文件:
String _filePath;
void getFilePath() async {
try {
String filePath = await FilePicker.getFilePath(
type: FileType.CUSTOM, fileExtension: 'csv');
if (filePath == '') {
return;
}
print("Path: " + filePath);
setState(() {
this._filePath = filePath;
});
} on PlatformException catch (e) {
print("Error picking file: " + e.toString());
}
}
使用上面的代码返回文件的路径,例如“/storage/emulated/0/Download/1.csv”。
现在我使用这个路径来读取文件的内容:
...
RaisedButton(
child: const Text('Import data - dummy'),
color: Theme.of(context).accentColor,
elevation: 4.0,
splashColor: Colors.blueGrey,
onPressed: () {
print('Verifying click done');
// Show contents of the file
readContents();
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getFilePath,
tooltip: 'Choose file to import',
child: new Icon(Icons.sd_storage),
)
...
Future<File> get _localFile async {
final path = await _filePath;
return File('$path');
}
Future<int> readContents() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If we encounter an error, return 0
return 0;
}
}
现在因为上面的代码应该返回一个 CSV 文件的内容,它什么也不做。CSV 文件包含项目列表。
有人可以让我知道为什么,并且好心地告诉我如何将文件的解析内容保存到一个字符串,甚至是更好的字符串来代表文件中的每一列吗?
谢谢!