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.
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)),
],
),
),
),
);
}
}