import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class SimpleNoteSaver extends StatefulWidget {
@override
_SimpleNoteSaverState createState() => _SimpleNoteSaverState();
}
class _SimpleNoteSaverState extends State<SimpleNoteSaver> {
final TextEditingController _controller = TextEditingController();
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/note.txt');
}
Future<void> _saveNote() async {
try {
final file = await _localFile;
await file.writeAsString(_controller.text);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Note saved')),
);
} catch (e) {
print('Error saving note: $e');
}
}
Future<void> _loadNote() async {
try {
final file = await _localFile;
String contents = await file.readAsString();
setState(() {
_controller.text = contents;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Note loaded')),
);
} catch (e) {
print('Error loading note: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('No saved note found')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Simple Note Saver')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Expanded(
child: TextField(
controller: _controller,
maxLines: null,
expands: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Type your note here...',
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _saveNote,
child: Text('Save Note'),
),
ElevatedButton(
onPressed: _loadNote,
child: Text('Load Note'),
),
],
),
],
),
),
);
}
}
This app uses the path_provider package to find a safe place on the device to store files. We get the documents directory path asynchronously.
We create a file named note.txt in that directory to save the note text.
The _saveNote method writes the current text from the TextField to the file. It shows a small message when done.
The _loadNote method reads the text from the file and updates the TextField with it. If no file exists, it shows a message.
Both methods handle errors by printing them to the console and showing user-friendly SnackBars.
This keeps the UI simple and responsive while demonstrating basic file storage in Flutter.