3

我的目标是从手机本地存储 ~/Downloads 打开一个 CSV 文件并将其导入数据库。

我正在使用 Flutter,到目前为止,我已经查看了十几个示例,但都没有成功。

但是,我能够在控制台中打印文件的内容,但为此我必须在应用程序项目的 assets/res 文件夹中有一个文件。

如果我使用 getExternalStorageDirectory,我会得到 emulated/storage/0/。如何访问设备的内部存储(不是外部存储,因为使用的手机没有 SD 卡选项,或者如果有,则不会使用)?

对于数据库,我能够使用 sqflite 获得一个工作示例,但我完全是菜鸟,我无法让它在我已经设计的应用程序中工作。

4

2 回答 2

2

使用 package:open_file/open_file.dart 中的 open_file 将文件作为文本文档打开并自己解析内容。

https://pub.dartlang.org/documentation/open_file/latest/

于 2019-01-10T07:46:50.780 回答
1

回到开始,但更接近我需要的解决方案。我有 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 文件包含项目列表。

有人可以让我知道为什么,并且好心地告诉我如何将文件的解析内容保存到一个字符串,甚至是更好的字符串来代表文件中的每一列吗?

谢谢!

于 2019-01-21T19:30:52.163 回答