Rick
Rick

Reputation: 279

Saving an excel file to a device using Flutter

I'm would like to save an excel file that I generate on the fly in a flutter app. I want to save the file on the users device, which is going to be on a mobile. However, I'm trying to figure out where and how to save it.

This is what I have so far using this excel package from flutter:

https://pub.dev/packages/excel

// Some function code...

// Trying to save the file somewhere on a device
excel.encode().then((onValue) {
      File("/some/filepath/but/not/sure/where/it/should/go")
      ..createSync(recursive: true)
      ..writeAsBytesSync(onValue);
    });

Anyone know the best way to do this?

Upvotes: 2

Views: 11743

Answers (1)

eeqk
eeqk

Reputation: 3862

According to Read and write files cookbook: https://flutter.dev/docs/cookbook/persistence/reading-writing-files

you need to follow these steps:

  1. Find the correct local path.
    • include path_provider in pubspec.yaml
    • compute a path to destination parent directory, for example documents dir:
Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}
  1. Create a reference to the file location.
Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/filename.xlsx');
}
  1. Write data to the file.
Future<File> writeCounter(Excel excel) async {
  final file = await _localFile;
  return file.writeAsBytes(excel.encode());
}

Upvotes: 2

Related Questions