Notes: 10. Exporting Data
Android Studio
Open up pubspec.yaml add add the following plugin:
file_picker: ^5.2.5
Run pub get to download the plugin.
Open up menus.dart and find the handleExport method. Add
final path = await FilePicker.platform.getDirectoryPath();
This will open up a System Folder picker window and will wait for the user to pick a folder. Now add:
// 1
if (path != null) {
// 2
final file = File('$path/exports.todo');
// 3
if (await file.exists()) {
await file.delete();
}
// 4
final repository = ref.read(repositoryProvider);
final todoController = ref.read(todoControllerProvider);
final todoLists = todoController.todoList;
final jsonList = <TodoList>[];
await Future.forEach(todoLists, (list) async {
jsonList.add(await repository.fillTodoList(list));
});
await file.writeAsString(jsonEncode(jsonList));
}
We first check to make sure that we have a path. Then we append the ‘exports.todo’ file name to the end of the directory. If the file already exists, delete it as we will be creating a new file. Next use Riverpod to find our repository and todo controller. The repository is for storing our todos and the TodoController has our current todo list. Next, go through each list and add the data to the list since the list only has it’s own data. Once we have all the data, we use jsonEncode to encode the list to a json string.
Now run the app, create some todo lists, categories and todos and then choose the File -> export menu. Choose the current directory and check it’s value.
Finder
On the Mac, open up the file and you can see the json the export command created.
You could use this as a way to store files or for backups. In the next episode you will see how to import this file.