forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
complete-crud-app-in-flutter.dart
424 lines (381 loc) · 10.9 KB
/
complete-crud-app-in-flutter.dart
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart'
show getApplicationDocumentsDirectory;
class Person implements Comparable {
final int id;
final String firstName;
final String lastName;
const Person(this.id, this.firstName, this.lastName);
String get fullName => '$firstName $lastName';
Person.fromData(Map<String, Object?> data)
: id = data['ID'] as int,
firstName = data['FIRST_NAME'] as String,
lastName = data['LAST_NAME'] as String;
@override
int compareTo(covariant Person other) => other.id.compareTo(id);
@override
bool operator ==(covariant Person other) => id == other.id;
@override
String toString() =>
'Person, ID = $id, firstName = $firstName, lastName = $lastName';
}
class PersonDB {
final _controller = StreamController<List<Person>>.broadcast();
List<Person> _persons = [];
Database? _db;
final String dbName;
PersonDB({required this.dbName});
Future<bool> close() async {
final db = _db;
if (db == null) {
return false;
}
await db.close();
return true;
}
Future<bool> open() async {
if (_db != null) {
return true;
}
final directory = await getApplicationDocumentsDirectory();
final path = '${directory.path}/$dbName';
try {
final db = await openDatabase(path);
_db = db;
// create the table if it doesn't exist
final create = '''CREATE TABLE IF NOT EXISTS PEOPLE (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
FIRST_NAME STRING NOT NULL,
LAST_NAME STRING NOT NULL
)''';
await db.execute(create);
// if everything went fine, we then read all the objects
// and populate the stream
_persons = await _fetchPeople();
_controller.add(_persons);
return true;
} catch (e) {
print('error = $e');
return false;
}
}
Future<List<Person>> _fetchPeople() async {
final db = _db;
if (db == null) {
return [];
}
try {
// read the existing data if any
final readResult = await db.query(
'PEOPLE',
distinct: true,
columns: ['ID', 'FIRST_NAME', 'LAST_NAME'],
orderBy: 'ID',
);
final people = readResult.map((row) => Person.fromData(row)).toList();
return people;
} catch (e) {
print('error = $e');
return [];
}
}
Future<bool> delete(Person person) async {
final db = _db;
if (db == null) {
return false;
}
try {
final deletedCount = await db.delete(
'PEOPLE',
where: 'ID = ?',
whereArgs: [person.id],
);
// delete it locally as well
if (deletedCount == 1) {
_persons.remove(person);
_controller.add(_persons);
return true;
} else {
return false;
}
} catch (e) {
print('Error inserting $e');
return false;
}
}
Future<bool> create(String firstName, String lastName) async {
final db = _db;
if (db == null) {
return false;
}
try {
final id = await db.insert(
'PEOPLE',
{
'FIRST_NAME': firstName,
'LAST_NAME': lastName,
},
);
final person = Person(id, firstName, lastName);
_persons.add(person);
_controller.add(_persons);
return true;
} catch (e) {
print('Error inserting $e');
return false;
}
}
// uses the person's id to update its first name and last name
Future<bool> update(Person person) async {
final db = _db;
if (db == null) {
return false;
}
try {
final updatedCount = await db.update(
'PEOPLE',
{
'FIRST_NAME': person.firstName,
'LAST_NAME': person.lastName,
},
where: 'ID = ?',
whereArgs: [person.id],
);
if (updatedCount == 1) {
_persons.removeWhere((p) => p.id == person.id);
_persons.add(person);
_controller.add(_persons);
return true;
} else {
return false;
}
} catch (e) {
print('Error inserting $e');
return false;
}
}
Stream<List<Person>> all() =>
_controller.stream.map((event) => event..sort());
}
typedef OnCompose = void Function(String firstName, String lastName);
class ComposeWidget extends StatefulWidget {
final OnCompose onCompose;
const ComposeWidget({Key? key, required this.onCompose}) : super(key: key);
@override
State<ComposeWidget> createState() => _ComposeWidgetState();
}
class _ComposeWidgetState extends State<ComposeWidget> {
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
@override
void dispose() {
firstNameController.dispose();
lastNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter first name',
),
controller: firstNameController,
),
TextField(
style: TextStyle(fontSize: 24),
decoration: InputDecoration(
hintText: 'Enter last name',
),
controller: lastNameController,
),
TextButton(
onPressed: () {
final firstName = firstNameController.text;
final lastName = lastNameController.text;
widget.onCompose(firstName, lastName);
},
child: Text(
'Add to list',
style: TextStyle(fontSize: 24),
),
),
]),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final PersonDB _crudStorage;
@override
void initState() {
_crudStorage = PersonDB(dbName: 'db.sqlite');
_crudStorage.open();
super.initState();
}
@override
void dispose() {
_crudStorage.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SQLite in Flutter'),
),
body: StreamBuilder(
stream: _crudStorage.all(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
if (snapshot.data == null) {
return Center(child: CircularProgressIndicator());
}
final people = snapshot.data as List<Person>;
return Column(
children: [
ComposeWidget(
onCompose: (firstName, lastName) async {
await _crudStorage.create(firstName, lastName);
},
),
Expanded(
child: ListView.builder(
itemCount: people.length,
itemBuilder: (context, index) {
final person = people[index];
return ListTile(
onTap: () async {
final update =
await showUpdateDialog(context, person);
if (update == null) {
return;
}
await _crudStorage.update(update);
},
title: Text(
person.fullName,
style: TextStyle(fontSize: 24),
),
subtitle: Text(
'ID: ${person.id}',
style: TextStyle(fontSize: 18),
),
trailing: TextButton(
onPressed: () async {
final shouldDelete =
await showDeleteDialog(context);
if (shouldDelete) {
await _crudStorage.delete(person);
}
},
child: Icon(
Icons.disabled_by_default_rounded,
color: Colors.red,
),
),
);
},
),
),
],
);
default:
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
Future<Person?> showUpdateDialog(BuildContext context, Person person) {
firstNameController.text = person.firstName;
lastNameController.text = person.lastName;
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Enter your udpated values here:'),
TextField(controller: firstNameController),
TextField(controller: lastNameController),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text('Cancel'),
),
TextButton(
onPressed: () {
final newPerson = Person(
person.id,
firstNameController.text,
lastNameController.text,
);
Navigator.of(context).pop(newPerson);
},
child: Text('Save'),
),
],
);
},
).then((value) {
if (value is Person) {
return value;
} else {
return null;
}
});
}
Future<bool> showDeleteDialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Are you sure you want to delete this item?'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Delete'),
)
],
);
},
).then(
(value) {
if (value is bool) {
return value;
} else {
return false;
}
},
);
}