Project: Notes App with SQLite
What We Build
A notes app that works fully offline. You can add, edit and delete notes, search by text, and your notes stay after you close the app. We use sqflite for storage and provider for state.
Step 1: Setup
bash
flutter create notes_app
cd notes_app
flutter pub add sqflite path provider
Platforms:
sqflite supports Android and iOS (and macOS). For Windows, Linux or web, you need a different setup such as sqflite_common_ffi. Test this project on an Android emulator or iOS simulator.
Step 2: Model and Database
Use the Note model and NotesDatabase helper from the SQLite lesson, with one extra method for searching, and put them in lib/data/.
dart
// lib/data/note.dart
class Note {
final int? id;
final String title;
final String body;
final DateTime updatedAt;
const Note({this.id, required this.title, required this.body, required this.updatedAt});
Note copyWith({String? title, String? body}) => Note(
id: id,
title: title ?? this.title,
body: body ?? this.body,
updatedAt: DateTime.now(),
);
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'body': body,
'updated_at': updatedAt.millisecondsSinceEpoch,
};
factory Note.fromMap(Map<String, Object?> m) => Note(
id: m['id'] as int?,
title: m['title'] as String,
body: m['body'] as String,
updatedAt: DateTime.fromMillisecondsSinceEpoch(m['updated_at'] as int),
);
}
dart
// lib/data/notes_database.dart
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'note.dart';
class NotesDatabase {
NotesDatabase._();
static final NotesDatabase instance = NotesDatabase._();
Database? _db;
Future<Database> get _database async => _db ??= await _open();
Future<Database> _open() async {
final path = join(await getDatabasesPath(), 'notes_app.db');
return openDatabase(
path,
version: 1,
onCreate: (db, _) => db.execute(
'CREATE TABLE notes ('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT NOT NULL, '
'updated_at INTEGER NOT NULL)',
),
);
}
Future<List<Note>> getNotes({String query = ''}) async {
final db = await _database;
final rows = await db.query(
'notes',
where: query.isEmpty ? null : 'title LIKE ? OR body LIKE ?',
whereArgs: query.isEmpty ? null : ['%$query%', '%$query%'],
orderBy: 'updated_at DESC',
);
return rows.map(Note.fromMap).toList();
}
Future<void> insert(Note note) async {
final db = await _database;
final map = note.toMap()..remove('id');
await db.insert('notes', map);
}
Future<void> update(Note note) async {
final db = await _database;
await db.update('notes', note.toMap(), where: 'id = ?', whereArgs: [note.id]);
}
Future<void> delete(int id) async {
final db = await _database;
await db.delete('notes', where: 'id = ?', whereArgs: [id]);
}
}
Step 3: The Provider
dart
// lib/state/notes_provider.dart
import 'package:flutter/foundation.dart';
import '../data/note.dart';
import '../data/notes_database.dart';
class NotesProvider extends ChangeNotifier {
final _db = NotesDatabase.instance;
List<Note> _notes = [];
String _query = '';
bool _loading = true;
List<Note> get notes => _notes;
bool get loading => _loading;
Future<void> load() async {
_loading = true;
notifyListeners();
_notes = await _db.getNotes(query: _query);
_loading = false;
notifyListeners();
}
Future<void> search(String text) async {
_query = text.trim();
await load();
}
Future<void> save(Note note) async {
if (note.id == null) {
await _db.insert(note);
} else {
await _db.update(note);
}
await load();
}
Future<void> delete(Note note) async {
if (note.id == null) return;
await _db.delete(note.id!);
await load();
}
}
Step 4: main.dart
dart
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'pages/notes_page.dart';
import 'state/notes_provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => NotesProvider()..load(),
child: MaterialApp(
title: 'Notes',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.amber)),
home: const NotesPage(),
),
),
);
}
Step 5: The Notes List Page
dart
// lib/pages/notes_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../data/note.dart';
import '../state/notes_provider.dart';
import 'edit_page.dart';
class NotesPage extends StatelessWidget {
const NotesPage({super.key});
void _open(BuildContext context, [Note? note]) {
Navigator.push(context, MaterialPageRoute(builder: (_) => EditPage(note: note)));
}
Future<bool> _confirm(BuildContext context) async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Delete note?'),
content: const Text('This cannot be undone.'),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Delete')),
],
),
);
return ok ?? false;
}
@override
Widget build(BuildContext context) {
final provider = context.watch<NotesProvider>();
return Scaffold(
appBar: AppBar(
title: const Text('Notes'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(64),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: SearchBar(
hintText: 'Search notes',
leading: const Icon(Icons.search),
onChanged: (text) => context.read<NotesProvider>().search(text),
),
),
),
),
body: provider.loading
? const Center(child: CircularProgressIndicator())
: provider.notes.isEmpty
? const Center(child: Text('No notes yet. Tap + to write one.'))
: GridView.builder(
padding: const EdgeInsets.all(12),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 260,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
childAspectRatio: 1.1,
),
itemCount: provider.notes.length,
itemBuilder: (context, i) {
final note = provider.notes[i];
return Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _open(context, note),
onLongPress: () async {
final notes = context.read<NotesProvider>();
if (await _confirm(context)) notes.delete(note);
},
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(note.title.isEmpty ? '(No title)' : note.title,
maxLines: 1, overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 6),
Expanded(
child: Text(note.body, overflow: TextOverflow.fade),
),
],
),
),
),
);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _open(context),
icon: const Icon(Icons.add),
label: const Text('New note'),
),
);
}
}
Step 6: The Edit Page
dart
// lib/pages/edit_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../data/note.dart';
import '../state/notes_provider.dart';
class EditPage extends StatefulWidget {
final Note? note;
const EditPage({super.key, this.note});
@override
State<EditPage> createState() => _EditPageState();
}
class _EditPageState extends State<EditPage> {
late final TextEditingController _title;
late final TextEditingController _body;
@override
void initState() {
super.initState();
_title = TextEditingController(text: widget.note?.title ?? '');
_body = TextEditingController(text: widget.note?.body ?? '');
}
@override
void dispose() {
_title.dispose();
_body.dispose();
super.dispose();
}
Future<void> _save() async {
final title = _title.text.trim();
final body = _body.text.trim();
if (title.isEmpty && body.isEmpty) {
Navigator.pop(context);
return;
}
final provider = context.read<NotesProvider>();
final navigator = Navigator.of(context);
final note = widget.note == null
? Note(title: title, body: body, updatedAt: DateTime.now())
: widget.note!.copyWith(title: title, body: body);
await provider.save(note);
navigator.pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.note == null ? 'New note' : 'Edit note'),
actions: [IconButton(icon: const Icon(Icons.check), onPressed: _save)],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _title,
style: Theme.of(context).textTheme.titleLarge,
decoration: const InputDecoration(hintText: 'Title', border: InputBorder.none),
),
Expanded(
child: TextField(
controller: _body,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
decoration: const InputDecoration(hintText: 'Write your note...', border: InputBorder.none),
),
),
],
),
),
);
}
}
What You Practiced
- Complete CRUD with SQLite
- Separation: database class, provider and pages
- Search with a SQL
LIKEquery and parameters - Safe use of
BuildContextafterawaitby storing the navigator and provider first - Material 3
SearchBarandFloatingActionButton.extended
Challenges
- Add a color or a pin to each note
- Add undo with a SnackBar after delete
- Export notes to a text file with
path_provider - Sync notes to Firestore for cloud backup
- Write tests that use an in-memory fake database
Conclusion
You now have four complete apps in your portfolio. Notice the repeating structure: a model, a data layer, a state class and simple screens.
Quick Summary: SQLite for storage, a Provider for state, a list page with search and an edit page. Always keep database code out of the widgets.

