Newer
Older
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'datamodel.dart';
import 'databaseconnector.dart';
import 'dart:async';
class EditEvent extends StatefulWidget {
const EditEvent({Key? key}) : super(key: key);
@override
State<EditEvent> createState() => _EditEventPageState();
}
class _EditEventPageState extends State<EditEvent> {
bool _initialized = false;
late String long = "";
late String lat = "";
late String alt = "";
late double accuracy = 0.0;
final prefs = SharedPreferences.getInstance(); // Is async
var database = DatabaseInstance();
late Event editEvent;
late OverlayEntry _overlayEntry; //For event creation success notifications
late Timer _overlayCloseTimer;
@override
void initState() {
super.initState();
}
@override
void dispose() async {
try {
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
}catch(e){
debugPrint('Dispose error on overlay remove: ' + e.toString());
}
super.dispose();
}
bool _validateLatitude(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
if (number >= -90.0 && number <= 90.0){
return true; // Latitude valid
}
}
return false;
}
bool _validateLongitude(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
if (number >= -180.0 && number <= 180.0){
return true; // Longitude valid
}
}
return false;
}
bool _validateElevation(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
return true; // Any numerical value is valid for elevation
}
return false;
}
bool _validateInput(Event event){
if (RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
event.label)) {
if (RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
event.description) || event.description == '') {
if(_validateLatitude(event.latitude)){
if(_validateLongitude(event.longitude)){
if(_validateElevation(event.elevation)){
return true;
}
}
}
}
}
return false;
}
Future<void> _showResultPopup(BuildContext context, String text, bool error) async {
OverlayState? overlayState = Overlay.of(context);
try {
_overlayEntry.remove(); // Allow only one Overlay Popup at a time
}catch(e){
debugPrint('Overlay already removed, during dispose: ' + e.toString());
}
_overlayEntry = OverlayEntry(builder: (context) {
Color backGroundColor;
Color textColor;
if (error == true){
backGroundColor = Colors.redAccent; //Style for error message
textColor = Colors.black;
}
else {
backGroundColor = Colors.greenAccent; //Style for notification
textColor = Colors.black;
}
return Stack(
alignment: Alignment.center,
children: [
Positioned(
// Position at 10% of height from bottom
bottom: MediaQuery.of(context).size.height * 0.1,
child: Material(
borderRadius: BorderRadius.circular(8.0),
color: backGroundColor, //Some transparency remains
child: Container(
padding: const EdgeInsets.all(5.0), // Space between Text and Bubble
width: MediaQuery.of(context).size.width * 0.95,
child: TextFormField(
minLines: 1,
maxLines: 5,
readOnly: true,
autofocus: false,
enabled: false,
style: TextStyle(color: textColor),
controller: TextEditingController(
text: text,
),
),
),
),
),
],
);
});
overlayState?.insert(_overlayEntry);
try {
_overlayCloseTimer.cancel(); // Kill old timers
}catch(e){
debugPrint('Timer cancel error: ' + e.toString());
}
_overlayCloseTimer = Timer(
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
() {
try {
_overlayEntry.remove(); // Allow only one Overlay Popup. NOTE: Is this a quick an dirty or a proper solution?
}catch(e){
debugPrint('Overlay already removed, during dispose: ' + e.toString());
}
},
);
}
Future<void> _updateOpenEvent(BuildContext context) async {
await database.updateEvent(editEvent);
HapticFeedback.vibrate(); //Feedback that adding event succeeded
}
@override
Widget build(BuildContext context) {
/* Get singletons to access relevant data here.*/
final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
if(false == _initialized) {
_initialized = true;
final arguments = (ModalRoute
.of(context)
?.settings
.arguments ?? <String, dynamic>{}) as Map;
editEvent = Event.fromEvent(arguments['event']);
debugPrint("Build Event loaded");
}
if (configuration.initialized == true) {
return Scaffold(
appBar: AppBar(
title: const Text("Edit Event"),
actions: <Widget>[
Column(
),
],
),
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 5.0),
child:
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
const SizedBox(height: 10.0),
TextFormField(
initialValue: editEvent.label,
autovalidateMode: AutovalidateMode.always,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Label',
),
onChanged: (value){
editEvent.label = value;
setState(() {});
},
validator: (value) {
if (!RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
value!)) {
return "Only: a-z , A-Z , _ , 0-9 , ,(Comma) , ( , ) , + , - , . , :";
} else {
return null; // Entered Text is valid
}
},
),
const SizedBox(height: 15.0),
DropdownButtonFormField(
value: editEvent.type,
isExpanded: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Event Type',
),
items:
configuration.eventTypes.map((EventType event) {
return DropdownMenuItem(
value: event.name,
child: Text(event.name),
);
}).toList(),
onChanged: (value) {
editEvent.type = value.toString();
}
),
const SizedBox(height: 15.0),
DropdownButtonFormField(
value: editEvent.urn,
isDense: false,
isExpanded: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'URN',
),
items:
configuration.devices.map((Device device) {
return DropdownMenuItem(
value: device.urn,
child: Text(device.urn),
);
}).toList(),
onChanged: (value) {
editEvent.urn = value.toString();
editEvent.urnId =
configuration.getDeviceIdFromUrn(value.toString());
}
),
const SizedBox(height: 15.0),
TextFormField(
initialValue: editEvent.description,
autovalidateMode: AutovalidateMode.always,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Description'
),
onChanged: (value){
editEvent.description = value;
setState(() {});
},
validator: (value) {
if (!RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
value!)) {
if(value == ''){
return null; //An empty description is also allowed.
}
return "Only: a-z , A-Z , _ , 0-9 , ,(Comma) , ( , ) , + , - , . , :";
} else {
return null; // Entered Text is valid
}
},
),
const SizedBox(height: 15.0),
TextFormField(
controller: TextEditingController(
text: editEvent.startDate.substring(0, 19) + 'Z' //Do not show microseconds
),
readOnly: true,
decoration: const InputDecoration(
labelText: 'Start Timestamp',
border: OutlineInputBorder(),
),
onTap: () {
DatePicker.showDateTimePicker(context,
showTitleActions: true,
onConfirm: (date) {
//Only one field for start and end date.
var isoDate = date.toIso8601String();
editEvent.startDate = isoDate;
debugPrint('Start Date set to : $isoDate');
setState(() {});
},
currentTime: DateTime.now().toUtc(),
locale: LocaleType.en);
},
),
const SizedBox(height: 15.0),
TextFormField(
controller: TextEditingController(
text: editEvent.endDate.substring(0, 19) + 'Z' //Do not show microseconds
),
readOnly: true,
decoration: const InputDecoration(
labelText: 'End Timestamp',
border: OutlineInputBorder(),
),
onTap: () {
DatePicker.showDateTimePicker(context,
showTitleActions: true,
onConfirm: (date) {
//Only one field for start and end date.
var isoDate = date.toIso8601String();
editEvent.endDate = isoDate;
debugPrint('End Date set to : $isoDate');
setState(() {});
},
currentTime: DateTime.now().toUtc(),
locale: LocaleType.en);
},
),
const SizedBox(height: 15.0),
TextFormField(
readOnly: false,
enabled: true,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: editEvent.latitude.toString()),
decoration: const InputDecoration(
labelText: 'Latitude',
border: OutlineInputBorder(),
),
onChanged: (value) {
editEvent.latitude = value;
},
onFieldSubmitted: (value){
setState(() {});
},
validator: (value) {
if (value == "") {
return null; // Empty value is allowed
}
final number = num.tryParse(value!);
if (number != null){
if (number >= -90.0 && number <= 90.0){
return null; // Latitude valid
}
}
return "-90 => Latitude <= +90";
},
),
const SizedBox(height: 15.0),
TextFormField(
readOnly: false,
enabled: true,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: editEvent.longitude.toString()),
decoration: const InputDecoration(
labelText: 'Longitude',
border: OutlineInputBorder(),
),
onChanged: (value) {
editEvent.longitude = value;
},
onFieldSubmitted: (value){
setState(() {});
},
validator: (value) {
if (value == "") {
return null; // Empty value is allowed
}
final number = num.tryParse(value!);
if (number != null){
if (number >= -180.0 && number <= 180.0){
return null; // Longitude valid
}
}
return "-180 => Longitude <= +180";
},
),
const SizedBox(height: 15.0),
TextFormField(
readOnly: false,
enabled: true,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: editEvent.elevation.toString()),
decoration: const InputDecoration(
labelText: 'Elevation',
border: OutlineInputBorder(),
),
onChanged: (value) {
editEvent.elevation = value;
},
onFieldSubmitted: (value){
setState(() {});
},
validator: (value) {
if (value == "") {
return null; // Empty value is allowed
}
final number = num.tryParse(value!);
if (number != null){
return null; // Elevation valid
}
return "Only numerical values for elevation in [m]";
},
),
]
),
),
),
bottomNavigationBar:Container(
margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
child:
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton.extended(
heroTag: null,
tooltip: 'Cancel',
icon: null,
label: const Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
const SizedBox(width: 5.0),
_validateInput(editEvent) ?
FloatingActionButton.extended(
heroTag: null,
tooltip: 'Update selected event',
icon: null,
label: const Text('Update'),
onPressed: () {
if (_validateInput(editEvent)) {
_updateOpenEvent(context);
_showResultPopup(context, "Successfully updated Event !", false );
Navigator.pop(context);
}
},
) :
FloatingActionButton.extended(
heroTag: null,
tooltip: 'Update selected event',
icon: null,
backgroundColor: Colors.grey,
label: const Text('Update'),
onPressed: () {
},
),
const SizedBox(width: 5.0),
],
),
),
);
}else {
return Scaffold(
appBar: AppBar(title: const Text("Edit Event")),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Container(
margin: const EdgeInsets.all(10.0),
child:const Text(
'Check Configuration Page for initial setup!',
style: TextStyle(fontSize: 20)
),
),
],
),
);
}
}
}
//TODO: introduce more object orientation and reuse code between edit and add event!