0
0
Fluttermobile~5 mins

File storage in Flutter

Choose your learning style9 modes available
Introduction

File storage lets your app save data on the device. This helps keep information even after the app closes.

Saving user notes or documents locally on the device.
Storing images or files downloaded from the internet.
Keeping app settings or preferences that need to persist.
Caching data to improve app speed without internet.
Saving logs or reports generated by the app.
Syntax
Flutter
import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/filename.txt');
}

Future<void> writeData(String data) async {
  final file = await _localFile;
  await file.writeAsString(data);
}

Future<String> readData() async {
  try {
    final file = await _localFile;
    String contents = await file.readAsString();
    return contents;
  } catch (e) {
    return 'Error reading file';
  }
}

Use path_provider package to find safe storage locations.

File operations are asynchronous to avoid freezing the app.

Examples
This writes the text 'Hello Flutter!' to the file.
Flutter
final file = await _localFile;
await file.writeAsString('Hello Flutter!');
This reads the text content from the file.
Flutter
final file = await _localFile;
String content = await file.readAsString();
This gets a temporary folder path for short-term files.
Flutter
final directory = await getTemporaryDirectory();
print(directory.path);
Sample App

This app has two buttons: one to save text to a file, and one to read it back. The saved text shows below the buttons.

Flutter
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _data = '';

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/data.txt');
  }

  Future<void> _writeData(String data) async {
    final file = await _localFile;
    await file.writeAsString(data);
  }

  Future<void> _readData() async {
    try {
      final file = await _localFile;
      String contents = await file.readAsString();
      setState(() {
        _data = contents;
      });
    } catch (e) {
      setState(() {
        _data = 'No data found.';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('File Storage Example')),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () async {
                  await _writeData('Hello from Flutter!');
                },
                child: Text('Write Data'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: _readData,
                child: Text('Read Data'),
              ),
              SizedBox(height: 20),
              Text('File content:'),
              SizedBox(height: 10),
              Text(_data, style: TextStyle(fontSize: 18)),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always handle errors when reading files to avoid crashes.

Files saved in app documents folder are private to your app.

Use asynchronous calls to keep the app responsive.

Summary

File storage saves data on the device to keep it between app uses.

Use path_provider to find safe folders for files.

Read and write files asynchronously to avoid freezing the app.