In Today’s tutorial, we will see how to handle files in Flutter.
Its so easy…
So Let’s start…
Below is the sample app we are going to create…
Watch Video Tutorial
Add Dependencies
For handling files in Flutter, we have to add a flutter dependency.
Go to the below link and read more about the dependency.
https://pub.dartlang.org/packages/path_provider#-readme-tab-
File Utility Class
For convenience let’s create a utility class for file operations. Create a new dart file named file_utils.dart. Our utility class is going to look like this. Here we are going to write to a file named “myfile.txt”.
Below are our utility functions for file operations.
- getFilePath :- Get the application’d Document’s directory.
- getFile :- Get the file descriptor from the Directory.
- saveToFile :- Save the data to the file.
- readFromFile :- Read the contents from the file.
import 'package:path_provider/path_provider.dart'; import 'dart:io'; class FileUtils { static Future<String> get getFilePath async { final directory = await getApplicationDocumentsDirectory(); return directory.path; } static Future<File> get getFile async { final path = await getFilePath; return File('$path/myfile.txt'); } static Future<File> saveToFile(String data) async { final file = await getFile; return file.writeAsString(data); } static Future<String> readFromFile() async { try { final file = await getFile; String fileContents = await file.readAsString(); return fileContents; } catch (e) { return ""; } } }
Now we are going to use this utility functions in our UI.
Our UI has a TextField, a button with onPress to save the data, Another button to read the data from the file and a label to show the contents of file.
UI
Here is the dart file which contains the UI.
import 'package:flutter/material.dart'; import 'file_utils.dart'; class FileOperationsScreen extends readAsString { FileOperationsScreen() : super(); final String title = "File Operations"; @override _FileOperationsScreenState createState() => _FileOperationsScreenState(); } class _FileOperationsScreenState extends State<FileOperationsScreen> { String fileContents = "No Data"; final myController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ TextField( controller: myController, ), RaisedButton( child: Text("Save To File"), onPressed: () { FileUtils.saveToFile(myController.text); }, ), RaisedButton( child: Text("Read From File"), onPressed: () { FileUtils.readFromFile().then((contents) { setState(() { fileContents = contents; }); }); }, ), Text(fileContents), ], ), ); } }
And That’s it. Leave your valuable comments below.
Thanks.