-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote_page.dart
More file actions
117 lines (105 loc) · 3.35 KB
/
note_page.dart
File metadata and controls
117 lines (105 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import 'package:flutter/material.dart';
import 'package:myapp/database_helper.dart';
import 'package:myapp/note.dart';
class NotePage extends StatefulWidget {
@override
_NotePageState createState() => _NotePageState();
}
class _NotePageState extends State<NotePage> {
List<Note> notes = [];
@override
void initState() {
super.initState();
_fetchNotes();
}
Future<void> _fetchNotes() async {
final noteMaps = await DatabaseHelper.instance.getNotes();
setState(() {
notes = noteMaps.map((map) => Note.fromMap(map)).toList();
});
}
Future<void> _addOrUpdateNote({Note? note}) async {
final TextEditingController titleController = TextEditingController(text: note?.title);
final TextEditingController contentController = TextEditingController(text: note?.content);
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(note == null ? 'Add Note' : 'Update Note'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: titleController,
decoration: InputDecoration(labelText: 'Title'),
),
TextField(
controller: contentController,
decoration: InputDecoration(labelText: 'Content'),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Cancel'),
),
TextButton(
onPressed: () async {
final title = titleController.text;
final content = contentController.text;
if (title.isEmpty || content.isEmpty) {
return;
}
final newNote = Note(
id: note?.id,
title: title,
content: content,
);
if (note == null) {
await DatabaseHelper.instance.insertNote(newNote.toMap());
} else {
await DatabaseHelper.instance.updateNote(newNote.toMap());
}
Navigator.of(context).pop();
_fetchNotes();
},
child: Text('Save'),
),
],
);
},
);
}
Future<void> _deleteNote(int id) async {
await DatabaseHelper.instance.deleteNote(id);
_fetchNotes();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Note Taking App'),
),
body: ListView.builder(
itemCount: notes.length,
itemBuilder: (context, index) {
final note = notes[index];
return ListTile(
title: Text(note.title),
subtitle: Text(note.content),
onTap: () => _addOrUpdateNote(note: note),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () => _deleteNote(note.id!),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _addOrUpdateNote(),
child: Icon(Icons.add),
),
);
}
}