Commit 29e9919
Changed files (96)
lib
components
dialoges
settings
model
blood_pressure
export_import
storage
platform_integration
screens
elements
subsettings
export_import
test
model
ui
components
settings
lib/components/dialoges/add_export_column_dialoge.dart
@@ -110,14 +110,14 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
segments: [
ButtonSegment(
value: _FormatterType.record,
- label: Text(localizations.recordFormat)
+ label: Text(localizations.recordFormat),
),
ButtonSegment(
value: _FormatterType.time,
- label: Text(localizations.timeFormat)
+ label: Text(localizations.timeFormat),
),
],
- selected: { type }
+ selected: { type },
),
const SizedBox(height: 8,),
Stack(
@@ -129,7 +129,7 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeIn,
- )),
+ ),),
child: _createTimeFormatInput(localizations, context),
),
SlideTransition(
@@ -139,7 +139,7 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeIn,
- )),
+ ),),
child: _createRecordFormatInput(localizations, context),
),
],
@@ -149,7 +149,7 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
- borderRadius: BorderRadius.circular(20)
+ borderRadius: BorderRadius.circular(20),
),
child: (){
final record = BloodPressureRecord(DateTime.now(), 123, 78, 65, 'test note');
@@ -159,20 +159,18 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
final decoded = formatter.decode(text);
return Column(
children: [
- (type == _FormatterType.record) ? MeasurementListRow(record: record, settings: widget.settings,)
- : Text(DateFormat('MMM d, y - h:m.s').format(record.creationTime)),
+ if (type == _FormatterType.record) MeasurementListRow(record: record, settings: widget.settings,) else Text(DateFormat('MMM d, y - h:m.s').format(record.creationTime)),
const SizedBox(height: 8,),
const Icon(Icons.arrow_downward),
const SizedBox(height: 8,),
- text.isNotEmpty ? Text(text) :
- Text(localizations.errNoValue, style: const TextStyle(fontStyle: FontStyle.italic),),
+ if (text.isNotEmpty) Text(text) else Text(localizations.errNoValue, style: const TextStyle(fontStyle: FontStyle.italic),),
const SizedBox(height: 8,),
const Icon(Icons.arrow_downward),
const SizedBox(height: 8,),
- Text(decoded.toString())
+ Text(decoded.toString()),
],
);
- }()
+ }(),
),
],
),
@@ -187,9 +185,8 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
String inputDocumentation,
String initialValue,
void Function(String) onChanged,
- String? Function(String?) validator
- ) {
- return Column(
+ String? Function(String?) validator,
+ ) => Column(
children: [
TextFormField(
initialValue: initialValue,
@@ -199,16 +196,15 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
suffixIcon: IconButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
- builder: (context) => InformationScreen(text: inputDocumentation)));
+ builder: (context) => InformationScreen(text: inputDocumentation),),);
},
- icon: const Icon(Icons.info_outline)
+ icon: const Icon(Icons.info_outline),
),
),
validator: validator,
- onSaved: (value) => onChanged),
+ onSaved: (value) => onChanged,),
],
);
- }
Column _createRecordFormatInput(AppLocalizations localizations, BuildContext context) =>
_createFormatInput(localizations,
@@ -220,7 +216,7 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
recordPattern = value;
}),
(value) => (type == _FormatterType.time || value != null && value.isNotEmpty) ? null
- : localizations.errNoValue
+ : localizations.errNoValue,
);
Column _createTimeFormatInput(AppLocalizations localizations, BuildContext context) =>
@@ -233,7 +229,7 @@ class _AddExportColumnDialogeState extends State<AddExportColumnDialoge> with Si
timePattern = value;
}),
(value) => (type == _FormatterType.record || (value != null && value.isNotEmpty)) ? null
- : localizations.errNoValue
+ : localizations.errNoValue,
);
void _saveForm() {
@@ -292,4 +288,4 @@ enum _FormatterType {
Future<ExportColumn?> showAddExportColumnDialoge(BuildContext context, Settings settings, [ExportColumn? initialColumn]) =>
showDialog<ExportColumn?>(context: context, builder: (context) => Dialog.fullscreen(
child: AddExportColumnDialoge(initialColumn: initialColumn, settings: settings,),
- ));
\ No newline at end of file
+ ),);
\ No newline at end of file
lib/components/dialoges/add_measurement_dialoge.dart
@@ -123,7 +123,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
context: context,
firstDate: DateTime.fromMillisecondsSinceEpoch(1),
lastDate: DateTime.now(),
- initialDate: time
+ initialDate: time,
);
if (selectedTime == null) {
return;
@@ -131,10 +131,10 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
final now = DateTime.now();
if (widget.settings.validateInputs && selectedTime.isAfter(now)) {
messenger.showSnackBar(SnackBar(
- content: Text(localizations.errTimeAfterNow)));
+ content: Text(localizations.errTimeAfterNow),),);
selectedTime = selectedTime.copyWith(
hour: max(selectedTime.hour, now.hour),
- minute: max(selectedTime.minute, now.minute)
+ minute: max(selectedTime.minute, now.minute),
);
}
setState(() {
@@ -193,7 +193,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
/// Build the border all fields have.
RoundedRectangleBorder buildShapeBorder([Color? color]) => RoundedRectangleBorder(
side: Theme.of(context).inputDecorationTheme.border?.borderSide ?? const BorderSide(width: 3),
- borderRadius: BorderRadius.circular(20)
+ borderRadius: BorderRadius.circular(20),
);
@override
@@ -251,7 +251,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
return AppLocalizations.of(context)?.errDiaGtSys;
}
return null;
- }
+ },
),
const SizedBox(width: 16,),
buildValueInput(localizations,
@@ -291,7 +291,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
});
},
initialColor: needlePin?.color ?? Colors.transparent,
- shape: buildShapeBorder(needlePin?.color)
+ shape: buildShapeBorder(needlePin?.color),
),
if (widget.settings.medications.isNotEmpty && widget.initialRecord == null)
Padding(
@@ -310,9 +310,8 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
child: Text(e.designation),
),
DropdownMenuItem(
- value: null,
child: Text(localizations.noMedication),
- )
+ ),
],
onChanged: (v) {
setState(() {
@@ -325,7 +324,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
medicineId = null;
}
});
- }
+ },
),
),
if (_showMedicineDosisInput)
@@ -344,7 +343,7 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
if(dosis != null && dosis > 0) medicineDosis = dosis;
}),
inputFormatters: [FilteringTextInputFormatter.allow(
- RegExp(r'([0-9]+(\.([0-9]*))?)'))],
+ RegExp(r'([0-9]+(\.([0-9]*))?)'),),],
validator: (String? value) {
if (!_showMedicineDosisInput) return null;
if (((int.tryParse(value ?? '')?.toDouble()
@@ -371,13 +370,13 @@ class _AddEntryDialogeState extends State<AddEntryDialoge> {
Future<(BloodPressureRecord?, MedicineIntake?)?> showAddEntryDialoge(
BuildContext context,
Settings settings,
- [BloodPressureRecord? initialRecord]) =>
+ [BloodPressureRecord? initialRecord,]) =>
showDialog<(BloodPressureRecord?, MedicineIntake?)>(
context: context, builder: (context) =>
Dialog.fullscreen(
child: AddEntryDialoge(
settings: settings,
- initialRecord: initialRecord
+ initialRecord: initialRecord,
),
- )
+ ),
);
\ No newline at end of file
lib/components/dialoges/add_medication_dialoge.dart
@@ -8,7 +8,7 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class AddMedicationDialoge extends StatefulWidget {
const AddMedicationDialoge({super.key,
- required this.settings
+ required this.settings,
});
final Settings settings;
@@ -43,8 +43,8 @@ class _AddMedicationDialogeState extends State<AddMedicationDialoge> {
widget.settings.highestMedIndex,
designation: _designation ?? '',
color: _color,
- defaultDosis: _defaultDosis
- ));
+ defaultDosis: _defaultDosis,
+ ),);
},
bottomAppBar: widget.settings.bottomAppBars,
body: Form(
@@ -79,22 +79,20 @@ class _AddMedicationDialogeState extends State<AddMedicationDialoge> {
);
}
- InputDecoration _getInputDecoration(BuildContext context, String? labelText) {
- return InputDecoration(
+ InputDecoration _getInputDecoration(BuildContext context, String? labelText) => InputDecoration(
hintText: labelText,
labelText: labelText,
errorMaxLines: 5,
border: _getBorder(),
enabledBorder: _getBorder(),
);
- }
OutlineInputBorder _getBorder() => OutlineInputBorder(
borderSide: BorderSide(
width: 3,
color: Theme.of(context).primaryColor,
),
- borderRadius: BorderRadius.circular(20)
+ borderRadius: BorderRadius.circular(20),
);
}
@@ -104,4 +102,4 @@ class _AddMedicationDialogeState extends State<AddMedicationDialoge> {
Future<Medicine?> showAddMedicineDialoge(BuildContext context, Settings settings) =>
showDialog<Medicine?>(context: context, builder: (context) => Dialog.fullscreen(
child: AddMedicationDialoge(settings: settings),
- ));
\ No newline at end of file
+ ),);
\ No newline at end of file
lib/components/dialoges/enter_timeformat_dialoge.dart
@@ -11,7 +11,7 @@ class EnterTimeFormatDialoge extends StatefulWidget {
const EnterTimeFormatDialoge({super.key,
required this.initialValue,
this.previewTime,
- this.bottomAppBars = false
+ this.bottomAppBars = false,
});
/// Text that is initially in time format field.
@@ -67,7 +67,7 @@ class _EnterTimeFormatDialogeState extends State<EnterTimeFormatDialoge> {
shrinkWrap: true,
onTapLink: getLinkTapHandler(context),
physics: const NeverScrollableScrollPhysics(),
- data: localizations.enterTimeFormatDesc
+ data: localizations.enterTimeFormatDesc,
),
Text(DateFormat(timeFormatFieldController.text).format(widget.previewTime ?? DateTime.now())),
Padding(
@@ -84,7 +84,7 @@ class _EnterTimeFormatDialogeState extends State<EnterTimeFormatDialoge> {
),
],
),
- )
+ ),
),
);
}
@@ -96,4 +96,4 @@ class _EnterTimeFormatDialogeState extends State<EnterTimeFormatDialoge> {
Future<String?> showTimeFormatPickerDialoge(BuildContext context, String initialTimeFormat, bool bottomAppBars) =>
showDialog<String?>(context: context, builder: (context) => Dialog.fullscreen(
child: EnterTimeFormatDialoge(initialValue: initialTimeFormat, bottomAppBars: bottomAppBars,),
- ));
\ No newline at end of file
+ ),);
\ No newline at end of file
lib/components/dialoges/fullscreen_dialoge.dart
@@ -47,7 +47,7 @@ class FullscreenDialoge extends StatelessWidget {
color: Colors.transparent,
shadowColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
- child: _buildAppBar(context)
+ child: _buildAppBar(context),
) : null,
);
@@ -61,9 +61,9 @@ class FullscreenDialoge extends StatelessWidget {
if (actionButtonText != null)
TextButton(
onPressed: onActionButtonPressed,
- child: Text(actionButtonText!)
- )
- ]
+ child: Text(actionButtonText!),
+ ),
+ ],
);
}
\ No newline at end of file
lib/components/dialoges/input_dialoge.dart
@@ -70,17 +70,17 @@ class _InputDialogeState extends State<InputDialoge> {
decoration: InputDecoration(
hintText: widget.hintText,
labelText: widget.hintText,
- errorText: errorText
+ errorText: errorText,
),
onSubmitted: _onSubmit,
),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(null),
- child: Text(localizations.btnCancel)),
+ child: Text(localizations.btnCancel),),
ElevatedButton(
onPressed: () => _onSubmit(controller.text),
- child: Text(localizations.btnConfirm)),
+ child: Text(localizations.btnConfirm),),
],
);
}
@@ -103,7 +103,7 @@ class _InputDialogeState extends State<InputDialoge> {
/// [initialValue] specifies the initial input field content.
Future<String?> showInputDialoge(BuildContext context, {String? hintText, String? initialValue}) async =>
showDialog<String?>(context: context, builder: (context) =>
- InputDialoge(hintText: hintText, initialValue: initialValue,));
+ InputDialoge(hintText: hintText, initialValue: initialValue,),);
/// Creates a dialoge that only allows int and double inputs.
///
@@ -123,7 +123,7 @@ Future<double?> showNumberInputDialoge(BuildContext context, {String? hintText,
}
return null;
},
- ));
+ ),);
double? value = double.tryParse(result ?? '');
value ??= int.tryParse(result ?? '')?.toDouble();
lib/components/measurement_list/intake_list_entry.dart
@@ -1,12 +1,11 @@
import 'dart:async';
+import 'package:blood_pressure_app/components/measurement_list/measurement_list_entry.dart';
import 'package:blood_pressure_app/model/blood_pressure/medicine/medicine_intake.dart';
import 'package:blood_pressure_app/model/storage/settings_store.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
-import 'measurement_list_entry.dart';
-
/// Medicine intake to display in a list.
class IntakeListEntry extends StatelessWidget {
/// Display a medicine intake on a list tile.
@@ -46,7 +45,7 @@ class IntakeListEntry extends StatelessWidget {
}
if (confirmedDeletion) delete!();
},
- icon: const Icon(Icons.delete)
+ icon: const Icon(Icons.delete),
),
],
),
lib/components/measurement_list/measurement_list.dart
@@ -48,25 +48,25 @@ class MeasurementList extends StatelessWidget {
children: [
const Expanded(
flex: 4,
- child: SizedBox()),
+ child: SizedBox(),),
Expanded(
flex: 30,
child: Text(localizations.sysLong,
overflow: TextOverflow.ellipsis,
- style: TextStyle(fontWeight: FontWeight.bold, color: settings.sysColor))),
+ style: TextStyle(fontWeight: FontWeight.bold, color: settings.sysColor),),),
Expanded(
flex: 30,
child: Text(localizations.diaLong,
overflow: TextOverflow.ellipsis,
- style: TextStyle(fontWeight: FontWeight.bold, color: settings.diaColor))),
+ style: TextStyle(fontWeight: FontWeight.bold, color: settings.diaColor),),),
Expanded(
flex: 30,
child: Text(localizations.pulLong,
overflow: TextOverflow.ellipsis,
- style: TextStyle(fontWeight: FontWeight.bold, color: settings.pulColor))),
+ style: TextStyle(fontWeight: FontWeight.bold, color: settings.pulColor),),),
const Expanded(
flex: 20,
- child: SizedBox()),
+ child: SizedBox(),),
],
),
const SizedBox(
@@ -76,8 +76,8 @@ class MeasurementList extends StatelessWidget {
height: 0,
thickness: 2,
color: Theme.of(context).colorScheme.primaryContainer,
- )
- ]
+ ),
+ ],
),
Expanded(
child: ListView.builder(
@@ -106,8 +106,8 @@ class MeasurementList extends StatelessWidget {
},
),
- )
- ]
+ ),
+ ],
);
}
}
\ No newline at end of file
lib/components/measurement_list/measurement_list_entry.dart
@@ -35,7 +35,7 @@ class MeasurementListRow extends StatelessWidget {
onPressed: () async {
final model = Provider.of<BloodPressureModel>(context, listen: false);
final entry = await showAddEntryDialoge(context,
- Provider.of<Settings>(context, listen: false));
+ Provider.of<Settings>(context, listen: false),);
if (entry?.$1 != null) {
if (context.mounted) {
model.addAndExport(context, entry!.$1!);
@@ -60,7 +60,7 @@ class MeasurementListRow extends StatelessWidget {
ListTile(
title: Text(localizations.note),
subtitle: Text(record.notes),
- )
+ ),
],
);
}
@@ -81,7 +81,7 @@ class MeasurementListRow extends StatelessWidget {
flex: 3,
child: Text(formatNum(record.pulse)),
),
- ]
+ ],
);
}
@@ -103,26 +103,24 @@ class MeasurementListRow extends StatelessWidget {
label: localizations.btnUndo,
onPressed: () => model.add(record),
),
- ));
+ ),);
}
}
}
-Future<bool> showConfirmDeletionDialoge(BuildContext context) async {
- return await showDialog<bool>(context: context,
+Future<bool> showConfirmDeletionDialoge(BuildContext context) async => await showDialog<bool>(context: context,
builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.confirmDelete),
content: Text(AppLocalizations.of(context)!.confirmDeleteDesc),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
- child: Text(AppLocalizations.of(context)!.btnCancel)
+ child: Text(AppLocalizations.of(context)!.btnCancel),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
- child: Text(AppLocalizations.of(context)!.btnConfirm)
+ child: Text(AppLocalizations.of(context)!.btnConfirm),
),
],
- )
+ ),
) ?? false;
-}
lib/components/settings/color_picker_list_tile.dart
@@ -12,7 +12,7 @@ class ColorSelectionListTile extends StatelessWidget {
required this.onMainColorChanged,
required this.initialColor,
this.subtitle,
- this.shape});
+ this.shape,});
/// The primary label of the list tile.
final Widget title;
@@ -30,8 +30,7 @@ class ColorSelectionListTile extends StatelessWidget {
final ShapeBorder? shape;
@override
- Widget build(BuildContext context) {
- return ListTile(
+ Widget build(BuildContext context) => ListTile(
title: title,
subtitle: subtitle,
shape: shape,
@@ -44,5 +43,4 @@ class ColorSelectionListTile extends StatelessWidget {
if (color != null) onMainColorChanged(color);
},
);
- }
}
\ No newline at end of file
lib/components/settings/dropdown_list_tile.dart
@@ -13,7 +13,7 @@ class DropDownListTile<T> extends StatefulWidget {
required this.items,
this.leading,
this.subtitle,
- super.key});
+ super.key,});
/// Primary description of the tile.
final Widget title;
@@ -48,14 +48,11 @@ class _DropDownListTileState<T> extends State<DropDownListTile<T>> {
}
@override
- Widget build(BuildContext context) {
- return ListTile(
+ Widget build(BuildContext context) => ListTile(
title: widget.title,
subtitle: widget.subtitle,
leading: widget.leading,
- onTap: () {
- focusNode.requestFocus();
- },
+ onTap: focusNode.requestFocus,
trailing: DropdownButton<T>(
focusNode: focusNode,
value: widget.value,
@@ -63,5 +60,4 @@ class _DropDownListTileState<T> extends State<DropDownListTile<T>> {
onChanged: widget.onChanged,
),
);
- }
}
\ No newline at end of file
lib/components/settings/input_list_tile.dart
@@ -7,7 +7,7 @@ class InputListTile extends StatelessWidget {
const InputListTile({super.key,
required this.label,
required this.value,
- required this.onSubmit});
+ required this.onSubmit,});
/// Short label describing the required field contents.
///
@@ -21,8 +21,7 @@ class InputListTile extends StatelessWidget {
final void Function(String text) onSubmit;
@override
- Widget build(BuildContext context) {
- return ListTile(
+ Widget build(BuildContext context) => ListTile(
title: Text(label),
subtitle: Text(value),
trailing: const Icon(Icons.edit),
@@ -31,6 +30,5 @@ class InputListTile extends StatelessWidget {
if (input != null) onSubmit(input);
},
);
- }
}
\ No newline at end of file
lib/components/settings/number_input_list_tile.dart
@@ -26,8 +26,7 @@ class NumberInputListTile extends StatelessWidget {
final void Function(double result) onParsableSubmit;
@override
- Widget build(BuildContext context) {
- return ListTile(
+ Widget build(BuildContext context) => ListTile(
title: Text(label),
subtitle: Text(value.toString()),
leading: leading,
@@ -35,10 +34,9 @@ class NumberInputListTile extends StatelessWidget {
onTap: () async {
final result = await showNumberInputDialoge(context,
initialValue: value,
- hintText: label
+ hintText: label,
);
if (result != null) onParsableSubmit(result);
},
);
- }
}
\ No newline at end of file
lib/components/settings/settings_widgets.dart
@@ -17,6 +17,7 @@
/// - [RadioListTile]
library settings_widgets;
+import 'package:blood_pressure_app/components/settings/settings_widgets.dart';
import 'package:flutter/material.dart';
export 'color_picker_list_tile.dart';
lib/components/settings/slider_list_tile.dart
@@ -13,7 +13,7 @@ class SliderListTile extends StatelessWidget {
required this.max,
this.stepSize = 1,
this.leading,
- this.trailing});
+ this.trailing,});
/// The primary content of the list tile.
final Widget title;
@@ -45,8 +45,7 @@ class SliderListTile extends StatelessWidget {
final void Function(double newValue) onChanged;
@override
- Widget build(BuildContext context) {
- return ListTile(
+ Widget build(BuildContext context) => ListTile(
title: title,
leading: leading,
trailing: trailing,
@@ -54,11 +53,10 @@ class SliderListTile extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
subtitle!,
- _buildSlider()
+ _buildSlider(),
],
),
);
- }
Widget _buildSlider() => SizedBox(
height: 30,
lib/components/settings/titled_column.dart
@@ -7,7 +7,7 @@ class TitledColumn extends StatelessWidget {
/// Useful for labeling sub lists.
const TitledColumn({super.key,
required this.title,
- required this.children});
+ required this.children,});
/// Title to display above the [children].
///
@@ -23,7 +23,7 @@ class TitledColumn extends StatelessWidget {
ListTile(
title: DefaultTextStyle(
style: Theme.of(context).textTheme.titleLarge!,
- child: title
+ child: title,
),
),
];
lib/components/color_picker.dart
@@ -11,7 +11,7 @@ class ColorPicker extends StatefulWidget {
this.availableColors,
this.initialColor,
this.showTransparentColor = true,
- this.circleSize = 50
+ this.circleSize = 50,
});
/// Colors to choose from.
@@ -69,7 +69,7 @@ class ColorPicker extends StatefulWidget {
Colors.deepOrangeAccent,
Colors.brown,
Colors.grey,
- Colors.blueGrey
+ Colors.blueGrey,
];
/// Size of the color circles.
@@ -91,8 +91,7 @@ class _ColorPickerState extends State<ColorPicker> {
availableColors = widget.availableColors ?? ColorPicker.allColors;
}
@override
- Widget build(BuildContext context) {
- return Wrap(
+ Widget build(BuildContext context) => Wrap(
children: [
for (final color in availableColors)
InkWell(
@@ -136,23 +135,20 @@ class _ColorPickerState extends State<ColorPicker> {
),
],
);
- }
}
/// Shows a dialog with a ColorPicker and with an cancel button inside.
///
/// Returns the selected color or null when cancel is pressed.
-Future<Color?> showColorPickerDialog(BuildContext context, [Color? initialColor]) async {
- return await showDialog(
+Future<Color?> showColorPickerDialog(BuildContext context, [Color? initialColor]) async => await showDialog(
context: context,
- builder: (_) {
- return AlertDialog(
+ builder: (_) => AlertDialog(
contentPadding: const EdgeInsets.all(6.0),
content: ColorPicker(
initialColor: initialColor,
onColorSelected: (color) {
Navigator.of(context).pop(color);
- }
+ },
),
actions: [
TextButton(
@@ -160,7 +156,5 @@ Future<Color?> showColorPickerDialog(BuildContext context, [Color? initialColor]
child: Text(AppLocalizations.of(context)!.btnCancel),
),
],
- );
- },
- );
-}
\ No newline at end of file
+ ),
+ );
\ No newline at end of file
lib/components/consistent_future_builder.dart
@@ -2,6 +2,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class ConsistentFutureBuilder<T> extends StatefulWidget {
+
+ const ConsistentFutureBuilder({super.key, required this.future, this.onNotStarted, this.onWaiting, this.onError,
+ required this.onData, this.cacheFuture = false, this.lastChildWhileWaiting = false,});
/// Future that gets evaluated.
final Future<T> future;
final Widget Function(BuildContext context, T result) onData;
@@ -24,9 +27,6 @@ class ConsistentFutureBuilder<T> extends StatefulWidget {
/// During the first build, [onWaiting] os respected instead.
final bool lastChildWhileWaiting;
- const ConsistentFutureBuilder({super.key, required this.future, this.onNotStarted, this.onWaiting, this.onError,
- required this.onData, this.cacheFuture = false, this.lastChildWhileWaiting = false});
-
@override
State<ConsistentFutureBuilder<T>> createState() => _ConsistentFutureBuilderState<T>();
}
@@ -45,8 +45,7 @@ class _ConsistentFutureBuilderState<T> extends State<ConsistentFutureBuilder<T>>
}
@override
- Widget build(BuildContext context) {
- return FutureBuilder<T>(
+ Widget build(BuildContext context) => FutureBuilder<T>(
future: _future ?? widget.future,
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
if (snapshot.hasError) {
@@ -63,6 +62,5 @@ class _ConsistentFutureBuilderState<T> extends State<ConsistentFutureBuilder<T>>
_lastChild = widget.onData(context, snapshot.data as T);
return _lastChild!;
}
- });
- }
+ },);
}
\ No newline at end of file
lib/components/date_time_picker.dart
@@ -17,7 +17,7 @@ Future<DateTime?> showDateTimePicker({
lastDate ??= firstDate.add(const Duration(days: 365 * 200));
final DateTime? selectedDate = await showDatePicker(
- context: context, initialDate: initialDate, firstDate: firstDate, lastDate: lastDate, confirmText: AppLocalizations.of(context)!.btnNext);
+ context: context, initialDate: initialDate, firstDate: firstDate, lastDate: lastDate, confirmText: AppLocalizations.of(context)!.btnNext,);
if (selectedDate == null) return null;
if (!context.mounted) return null;
lib/components/disabled.dart
@@ -23,7 +23,7 @@ class Disabled extends StatelessWidget {
child: IgnorePointer(
ignoring: ignoring,
child: child,
- )
+ ),
);
}
return child;
lib/model/blood_pressure/medicine/intake_history.dart
@@ -23,7 +23,7 @@ class IntakeHistory extends ChangeNotifier {
serialized
.split('\n')
.map((e) => MedicineIntake.deserialize(e, availableMedicines))
- .toList()
+ .toList(),
);
/// Serializes the current state of the object into a string.
@@ -57,7 +57,7 @@ class IntakeHistory extends ChangeNotifier {
///
/// Uses binary search to determine the bound.
void addIntake(MedicineIntake intake) {
- int index = _findUpperBound(_medicineIntakes, intake.timestamp);
+ final int index = _findUpperBound(_medicineIntakes, intake.timestamp);
if (index == -1) {
_medicineIntakes.add(intake);
lib/model/blood_pressure/medicine/medicine.dart
@@ -6,31 +6,31 @@ import 'package:flutter/material.dart';
/// Description of a specific medicine.
class Medicine {
+
+ factory Medicine.fromMap(Map<String, dynamic> map) => Medicine(
+ map['id'],
+ designation: map['designation'],
+ color: Color(map['color']),
+ defaultDosis: map['defaultDosis'],
+ );
+
+ factory Medicine.fromJson(String json) => Medicine.fromMap(jsonDecode(json));
/// Create a new medicine.
const Medicine(this.id, {
required this.designation,
required this.color,
- required this.defaultDosis
+ required this.defaultDosis,
});
Map<String, dynamic> toMap() => {
'id': id,
'designation': designation,
'color': color.value,
- 'defaultDosis': defaultDosis
+ 'defaultDosis': defaultDosis,
};
String toJson() => jsonEncode(toMap());
- factory Medicine.fromMap(Map<String, dynamic> map) => Medicine(
- map['id'],
- designation: map['designation'],
- color: Color(map['color']),
- defaultDosis: map['defaultDosis']
- );
-
- factory Medicine.fromJson(String json) => Medicine.fromMap(jsonDecode(json));
-
/// Unique id used to store the medicine in serialized objects.
final int id;
@@ -58,7 +58,5 @@ class Medicine {
int get hashCode => id.hashCode ^ designation.hashCode ^ color.hashCode ^ defaultDosis.hashCode;
@override
- String toString() {
- return 'Medicine{id: $id, designation: $designation, color: $color, defaultDosis: $defaultDosis}';
- }
+ String toString() => 'Medicine{id: $id, designation: $designation, color: $color, defaultDosis: $defaultDosis}';
}
lib/model/blood_pressure/medicine/medicine_intake.dart
@@ -3,11 +3,20 @@ import 'package:blood_pressure_app/model/blood_pressure/medicine/medicine.dart';
/// Instance of a medicine intake.
class MedicineIntake implements Comparable<Object> {
+
+ factory MedicineIntake.deserialize(String string, List<Medicine> availableMeds) {
+ final elements = string.split('\x00');
+ return MedicineIntake(
+ medicine: availableMeds.firstWhere((e) => e.id == int.parse(elements[0])),
+ timestamp: DateTime.fromMillisecondsSinceEpoch(int.parse(elements[1])),
+ dosis: double.parse(elements[2]),
+ );
+ }
/// Create a instance of a medicine intake.
const MedicineIntake({
required this.medicine,
required this.dosis,
- required this.timestamp
+ required this.timestamp,
});
/// Serialize the object to a deserializable string.
@@ -17,15 +26,6 @@ class MedicineIntake implements Comparable<Object> {
String serialize() =>
'${medicine.id}\x00${timestamp.millisecondsSinceEpoch}\x00$dosis';
- factory MedicineIntake.deserialize(String string, List<Medicine> availableMeds) {
- final elements = string.split('\x00');
- return MedicineIntake(
- medicine: availableMeds.firstWhere((e) => e.id == int.parse(elements[0])),
- timestamp: DateTime.fromMillisecondsSinceEpoch(int.parse(elements[1])),
- dosis: double.parse(elements[2]),
- );
- }
-
/// Kind of medicine taken.
final Medicine medicine;
@@ -48,7 +48,7 @@ class MedicineIntake implements Comparable<Object> {
int get hashCode => medicine.hashCode ^ dosis.hashCode ^ timestamp.hashCode;
@override
- int compareTo(other) {
+ int compareTo(Object other) {
assert(other is MedicineIntake);
if (other is! MedicineIntake) return 0;
@@ -59,7 +59,5 @@ class MedicineIntake implements Comparable<Object> {
}
@override
- String toString() {
- return 'MedicineIntake{medicine: $medicine, dosis: $dosis, timestamp: $timestamp}';
- }
+ String toString() => 'MedicineIntake{medicine: $medicine, dosis: $dosis, timestamp: $timestamp}';
}
\ No newline at end of file
lib/model/blood_pressure/model.dart
@@ -13,9 +13,9 @@ import 'package:provider/provider.dart';
import 'package:sqflite/sqflite.dart';
class BloodPressureModel extends ChangeNotifier {
- late final Database _database;
BloodPressureModel._create();
+ late final Database _database;
Future<void> _asyncInit(String? dbPath, bool isFullPath) async {
dbPath ??= await getDatabasesPath();
@@ -44,14 +44,12 @@ class BloodPressureModel extends ChangeNotifier {
);
}
- FutureOr<void> _onDBCreate(Database db, int version) {
- return db.execute('CREATE TABLE bloodPressureModel('
+ FutureOr<void> _onDBCreate(Database db, int version) => db.execute('CREATE TABLE bloodPressureModel('
'timestamp INTEGER(14) PRIMARY KEY,'
'systolic INTEGER, diastolic INTEGER,'
'pulse INTEGER,'
'notes STRING,'
'needlePin STRING)');
- }
FutureOr<void> _onDBUpgrade(Database db, int oldVersion, int newVersion) async {
// When adding more versions the upgrade procedure proposed in https://stackoverflow.com/a/75153875/21489239
@@ -81,7 +79,7 @@ class BloodPressureModel extends ChangeNotifier {
Future<void> add(BloodPressureRecord measurement) async {
if (!_database.isOpen) return;
final existing = await _database.query('bloodPressureModel',
- where: 'timestamp = ?', whereArgs: [measurement.creationTime.millisecondsSinceEpoch]);
+ where: 'timestamp = ?', whereArgs: [measurement.creationTime.millisecondsSinceEpoch],);
if (existing.isNotEmpty) {
await _database.update(
'bloodPressureModel',
@@ -90,10 +88,10 @@ class BloodPressureModel extends ChangeNotifier {
'diastolic': measurement.diastolic,
'pulse': measurement.pulse,
'notes': measurement.notes,
- 'needlePin': jsonEncode(measurement.needlePin)
+ 'needlePin': jsonEncode(measurement.needlePin),
},
where: 'timestamp = ?',
- whereArgs: [measurement.creationTime.millisecondsSinceEpoch]);
+ whereArgs: [measurement.creationTime.millisecondsSinceEpoch],);
} else {
await _database.insert('bloodPressureModel', {
'timestamp': measurement.creationTime.millisecondsSinceEpoch,
@@ -101,7 +99,7 @@ class BloodPressureModel extends ChangeNotifier {
'diastolic': measurement.diastolic,
'pulse': measurement.pulse,
'notes': measurement.notes,
- 'needlePin': jsonEncode(measurement.needlePin)
+ 'needlePin': jsonEncode(measurement.needlePin),
});
}
notifyListeners();
@@ -131,8 +129,8 @@ class BloodPressureModel extends ChangeNotifier {
final dbEntries = await _database.query('bloodPressureModel',
orderBy: 'timestamp DESC',
where: 'timestamp BETWEEN ? AND ?',
- whereArgs: [from.millisecondsSinceEpoch, to.millisecondsSinceEpoch]); // descending
- List<BloodPressureRecord> recordsInRange = _convert(dbEntries);
+ whereArgs: [from.millisecondsSinceEpoch, to.millisecondsSinceEpoch],); // descending
+ final List<BloodPressureRecord> recordsInRange = _convert(dbEntries);
return UnmodifiableListView(recordsInRange);
}
@@ -141,13 +139,11 @@ class BloodPressureModel extends ChangeNotifier {
return UnmodifiableListView(_convert(await _database.query('bloodPressureModel', columns: ['*'])));
}
- Future<void> close() {
- return _database.close();
- }
+ Future<void> close() => _database.close();
List<BloodPressureRecord> _convert(List<Map<String, Object?>> dbResult) {
- List<BloodPressureRecord> records = [];
- for (var e in dbResult) {
+ final List<BloodPressureRecord> records = [];
+ for (final e in dbResult) {
final needlePinJson = e['needlePin'] as String?;
final needlePin = (needlePinJson != null) ? jsonDecode(needlePinJson) : null;
records.add(BloodPressureRecord(
@@ -156,8 +152,8 @@ class BloodPressureModel extends ChangeNotifier {
e['diastolic'] as int?,
e['pulse'] as int?,
e['notes'].toString(),
- needlePin: (needlePin != null) ? MeasurementNeedlePin.fromJson(needlePin) : null
- ));
+ needlePin: (needlePin != null) ? MeasurementNeedlePin.fromJson(needlePin) : null,
+ ),);
}
return records;
}
lib/model/blood_pressure/needle_pin.dart
@@ -2,18 +2,16 @@ import 'package:flutter/material.dart';
@immutable
class MeasurementNeedlePin {
- final Color color;
const MeasurementNeedlePin(this.color);
// When updating this, remember to be backwards compatible
MeasurementNeedlePin.fromJson(Map<String, dynamic> json)
: color = Color(json['color']);
+ final Color color;
Map<String, dynamic> toJson() => {
'color': color.value,
};
@override
- String toString() {
- return 'MeasurementNeedlePin{$color}';
- }
+ String toString() => 'MeasurementNeedlePin{$color}';
}
\ No newline at end of file
lib/model/blood_pressure/record.dart
@@ -3,26 +3,24 @@ import 'package:flutter/material.dart';
@immutable
class BloodPressureRecord {
- late final DateTime creationTime;
- final int? systolic;
- final int? diastolic;
- final int? pulse;
- final String notes;
- final MeasurementNeedlePin? needlePin;
BloodPressureRecord(DateTime creationTime, this.systolic, this.diastolic, this.pulse, this.notes, {
- this.needlePin
+ this.needlePin,
}) {
if (creationTime.millisecondsSinceEpoch > 0) {
this.creationTime = creationTime;
} else {
- assert(false, "Tried to create BloodPressureRecord at or before epoch");
+ assert(false, 'Tried to create BloodPressureRecord at or before epoch');
this.creationTime = DateTime.fromMillisecondsSinceEpoch(1);
}
}
+ late final DateTime creationTime;
+ final int? systolic;
+ final int? diastolic;
+ final int? pulse;
+ final String notes;
+ final MeasurementNeedlePin? needlePin;
@override
- String toString() {
- return 'BloodPressureRecord($creationTime, $systolic, $diastolic, $pulse, $notes, $needlePin)';
- }
+ String toString() => 'BloodPressureRecord($creationTime, $systolic, $diastolic, $pulse, $notes, $needlePin)';
}
\ No newline at end of file
lib/model/export_import/column.dart
@@ -36,25 +36,25 @@ class NativeColumn extends ExportColumn {
'systolic',
RowDataFieldType.sys,
(record) => record.systolic.toString(),
- (pattern) => int.tryParse(pattern)
+ int.tryParse,
);
static final NativeColumn diastolic = NativeColumn._create(
'diastolic',
RowDataFieldType.dia,
(record) => record.diastolic.toString(),
- (pattern) => int.tryParse(pattern)
+ int.tryParse,
);
static final NativeColumn pulse = NativeColumn._create(
'pulse',
RowDataFieldType.pul,
(record) => record.pulse.toString(),
- (pattern) => int.tryParse(pattern)
+ int.tryParse,
);
static final NativeColumn notes = NativeColumn._create(
'notes',
RowDataFieldType.notes,
(record) => record.notes,
- (pattern) => pattern
+ (pattern) => pattern,
);
static final NativeColumn color = NativeColumn._create(
'color',
@@ -138,12 +138,12 @@ class BuildInColumn extends ExportColumn {
'buildin.pulsePressure',
'pulsePressure',
r'{{$SYS-$DIA}}',
- (localizations) => localizations.pulsePressure
+ (localizations) => localizations.pulsePressure,
);
static final formattedTime = TimeColumn.explicit(
'buildin.formattedTime',
'Time',
- 'dd MMM yyyy, HH:mm'
+ 'dd MMM yyyy, HH:mm',
);
// my heart columns
@@ -151,49 +151,49 @@ class BuildInColumn extends ExportColumn {
'buildin.mhDate',
'DATUM',
r'yyyy-MM-dd HH:mm:ss',
- '"My Heart" export time'
+ '"My Heart" export time',
);
static final mhSys = BuildInColumn._create(
'buildin.mhSys',
'SYSTOLE',
r'$SYS',
- (_) => '"My Heart" export sys'
+ (_) => '"My Heart" export sys',
);
static final mhDia = BuildInColumn._create(
'buildin.mhDia',
'DIASTOLE',
r'$DIA',
- (_) => '"My Heart" export dia'
+ (_) => '"My Heart" export dia',
);
static final mhPul = BuildInColumn._create(
'buildin.mhPul',
'PULSE',
r'$PUL',
- (_) => '"My Heart" export pul'
+ (_) => '"My Heart" export pul',
);
static final mhDesc = BuildInColumn._create(
'buildin.mhDesc',
'Beschreibung',
r'null',
- (_) => '"My Heart" export description'
+ (_) => '"My Heart" export description',
);
static final mhTags = BuildInColumn._create(
'buildin.mhTags',
'Tags',
r'',
- (_) => '"My Heart" export tags'
+ (_) => '"My Heart" export tags',
);
static final mhWeight = BuildInColumn._create(
'buildin.mhWeight',
'Gewicht',
r'0.0',
- (_) => '"My Heart" export weight'
+ (_) => '"My Heart" export weight',
);
static final mhOxygen = BuildInColumn._create(
'buildin.mhOxygen',
'Sauerstoffsättigung',
r'0',
- (_) => '"My Heart" export oxygen'
+ (_) => '"My Heart" export oxygen',
);
@override
lib/model/export_import/csv_converter.dart
@@ -25,15 +25,15 @@ class CsvConverter {
final columns = settings.exportFieldsConfiguration.getActiveColumns(availableColumns);
final table = records.map(
(record) => columns.map(
- (column) => column.encode(record)
- ).toList()
+ (column) => column.encode(record),
+ ).toList(),
).toList();
if (settings.exportHeadline) table.insert(0, columns.map((c) => c.csvTitle).toList());
final csvCreator = ListToCsvConverter(
fieldDelimiter: settings.fieldDelimiter,
- textDelimiter: settings.textDelimiter
+ textDelimiter: settings.textDelimiter,
);
return csvCreator.convert(table);
@@ -66,7 +66,7 @@ class CsvConverter {
final formattedTitleText = (titleText as String).trim();
final column = availableColumns.firstWhere(
(c) => c.csvTitle == formattedTitleText
- && c.restoreAbleType != null);
+ && c.restoreAbleType != null,);
if (column == null) return RecordParsingResult.err(RecordParsingErrorUnknownColumn(titleText));
columns.add(column);
}
@@ -96,21 +96,21 @@ class CsvConverter {
}
final DateTime? timestamp = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.timestamp)?.$2;
+ (piece) => piece.$1 == RowDataFieldType.timestamp,)?.$2;
if (timestamp == null) {
return RecordParsingResult.err(RecordParsingErrorTimeNotRestoreable());
}
final int? sys = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.sys)?.$2;
+ (piece) => piece.$1 == RowDataFieldType.sys,)?.$2;
final int? dia = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.dia)?.$2;
+ (piece) => piece.$1 == RowDataFieldType.dia,)?.$2;
final int? pul = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.pul)?.$2;
+ (piece) => piece.$1 == RowDataFieldType.pul,)?.$2;
final String note = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.notes)?.$2 ?? '';
- MeasurementNeedlePin? needlePin = recordPieces.firstWhereOrNull(
- (piece) => piece.$1 == RowDataFieldType.needlePin)?.$2;
+ (piece) => piece.$1 == RowDataFieldType.notes,)?.$2 ?? '';
+ final MeasurementNeedlePin? needlePin = recordPieces.firstWhereOrNull(
+ (piece) => piece.$1 == RowDataFieldType.needlePin,)?.$2;
records.add(BloodPressureRecord(timestamp, sys, dia, pul, note, needlePin: needlePin));
currentLineNumber++;
lib/model/export_import/export_configuration.dart
@@ -24,7 +24,7 @@ class ActiveExportColumnConfiguration extends ChangeNotifier {
final json = jsonDecode(jsonString);
return ActiveExportColumnConfiguration(
activePreset: ExportImportPreset.decode(json['preset']) ?? ExportImportPreset.bloodPressureApp,
- userSelectedColumnIds: ConvertUtil.parseList<String>(json['columns'])
+ userSelectedColumnIds: ConvertUtil.parseList<String>(json['columns']),
);
} on FormatException {
return ActiveExportColumnConfiguration();
@@ -34,7 +34,7 @@ class ActiveExportColumnConfiguration extends ChangeNotifier {
String toJson() => jsonEncode({
'columns': _userSelectedColumns,
- 'preset': _activePreset.encode()
+ 'preset': _activePreset.encode(),
});
/// The [UserColumn.internalIdentifier] of columns currently selected by user.
@@ -105,7 +105,7 @@ class ActiveExportColumnConfiguration extends ChangeNotifier {
NativeColumn.diastolic,
NativeColumn.pulse,
]
- });
+ },);
}
@@ -140,8 +140,7 @@ enum ExportImportPreset {
ExportImportPreset.bloodPressureAppPdf => 3,
};
- static ExportImportPreset? decode(dynamic e) {
- return switch(e) {
+ static ExportImportPreset? decode(e) => switch(e) {
0 => ExportImportPreset.none,
1 => ExportImportPreset.bloodPressureApp,
2 => ExportImportPreset.myHeart,
@@ -151,5 +150,4 @@ enum ExportImportPreset {
return null;
}(),
};
- }
}
\ No newline at end of file
lib/model/export_import/import_field_type.dart
@@ -1,3 +1,4 @@
+import 'package:blood_pressure_app/model/blood_pressure/needle_pin.dart';
import 'package:blood_pressure_app/model/export_import/record_formatter.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
lib/model/export_import/pdf_converter.dart
@@ -55,8 +55,8 @@ class PdfConverter {
_buildPdfTable(records, availableHeight),
];
},
- maxPages: 100
- ));
+ maxPages: 100,
+ ),);
return await pdf.save();
}
@@ -67,17 +67,16 @@ class PdfConverter {
child: pw.Text(
localizations.pdfDocumentTitle(
dateFormatter.format(analyzer.firstDay!),
- dateFormatter.format(analyzer.lastDay!)
+ dateFormatter.format(analyzer.lastDay!),
),
style: const pw.TextStyle(
fontSize: 16,
- )
- )
+ ),
+ ),
);
}
- pw.Widget _buildPdfStatistics(BloodPressureAnalyser analyzer) {
- return pw.Container(
+ pw.Widget _buildPdfStatistics(BloodPressureAnalyser analyzer) => pw.Container(
margin: const pw.EdgeInsets.all(20),
child: pw.TableHelper.fromTextArray(
data: [
@@ -85,22 +84,21 @@ class PdfConverter {
[localizations.average, analyzer.avgSys, analyzer.avgDia, analyzer.avgPul],
[localizations.maximum, analyzer.maxSys, analyzer.maxDia, analyzer.maxPul],
[localizations.minimum, analyzer.minSys, analyzer.minDia, analyzer.minPul],
- ]
+ ],
),
);
- }
pw.Widget _buildPdfTable(Iterable<BloodPressureRecord> records, double availableHeightOnFirstPage) {
final columns = pdfSettings.exportFieldsConfiguration.getActiveColumns(availableColumns);
final data = records.map(
(record) => columns.map(
- (column) => column.encode(record)
- ).toList()
+ (column) => column.encode(record),
+ ).toList(),
).toList();
return pw.Builder(builder: (
- pw.Context context) {
+ pw.Context context,) {
final realCellHeight = () {
final cell = pw.TableHelper.fromTextArray(
data: data,
@@ -126,7 +124,7 @@ class PdfConverter {
data: [],
border: null,
headerDecoration: const pw.BoxDecoration(
- border: pw.Border(bottom: pw.BorderSide(color: PdfColors.black))
+ border: pw.Border(bottom: pw.BorderSide()),
),
headerHeight: pdfSettings.headerHeight,
headerStyle: pw.TextStyle(
@@ -154,7 +152,7 @@ class PdfConverter {
border: null,
cellAlignment: pw.Alignment.centerLeft,
headerDecoration: const pw.BoxDecoration(
- border: pw.Border(bottom: pw.BorderSide(color: PdfColors.black))
+ border: pw.Border(bottom: pw.BorderSide()),
),
headerHeight: pdfSettings.headerHeight,
cellHeight: pdfSettings.cellHeight,
@@ -214,7 +212,7 @@ class PdfConverter {
border: null,
cellAlignment: pw.Alignment.centerLeft,
headerDecoration: const pw.BoxDecoration(
- border: pw.Border(bottom: pw.BorderSide(color: PdfColors.black))
+ border: pw.Border(bottom: pw.BorderSide()),
),
headerHeight: pdfSettings.headerHeight,
cellHeight: pdfSettings.cellHeight,
@@ -248,8 +246,8 @@ class PdfConverter {
),
headers: columns.map((c) => c.userTitle(localizations)).toList(),
data: dataRange,
- )
- ));
+ ),
+ ),);
pageNum++;
}
@@ -258,9 +256,9 @@ class PdfConverter {
children: [
for (final table in tables)
pw.Expanded(child: table),
- ]
+ ],
);
- }
+ },
);
}
}
lib/model/export_import/record_formatter.dart
@@ -78,7 +78,7 @@ class ScriptedFormatter implements Formatter {
fieldContents = fieldContents.replaceAll(r'$SYS', record.systolic.toString());
fieldContents = fieldContents.replaceAll(r'$DIA', record.diastolic.toString());
fieldContents = fieldContents.replaceAll(r'$PUL', record.pulse.toString());
- fieldContents = fieldContents.replaceAll(r'$NOTE', record.notes.toString());
+ fieldContents = fieldContents.replaceAll(r'$NOTE', record.notes);
fieldContents = fieldContents.replaceAll(r'$COLOR', jsonEncode(record.needlePin?.toJson()));
// math
@@ -92,7 +92,7 @@ class ScriptedFormatter implements Formatter {
fieldContents = fieldContents.replaceAllMapped(RegExp(r'\$FORMAT\{([^}]*)}'), (m) {
assert(m.groupCount == 1, 'If a FORMAT block is found a group is expected');
final bothArgs = m.group(1)!;
- int separatorPosition = bothArgs.indexOf(",");
+ final int separatorPosition = bothArgs.indexOf(',');
final timestamp = DateTime.fromMillisecondsSinceEpoch(int.parse(bothArgs.substring(0,separatorPosition)));
final formatPattern = bothArgs.substring(separatorPosition+1);
return DateFormat(formatPattern).format(timestamp);
@@ -120,7 +120,7 @@ class ScriptedFormatter implements Formatter {
@override
RowDataFieldType? get restoreAbleType {
- if (_hasRestoreableType == false) {
+ if (!_hasRestoreableType) {
final replaced = pattern.replaceFirst(RegExp(r'[^{},$]*\$(SYS|DIA|PUL)[^{},$]*'), '');
if (pattern.contains(RegExp(r'[{},]'))) {
_restoreAbleType = null;
lib/model/export_import/record_parsing_result.dart
@@ -3,10 +3,6 @@ import 'package:blood_pressure_app/model/blood_pressure/record.dart';
/// Indicate a possible error during record parsing.
class RecordParsingResult {
- RecordParsingResult._create(this._result, this._error);
-
- final List<BloodPressureRecord>? _result;
- final RecordParsingError? _error;
/// Pass a valid record list and indicate success.
factory RecordParsingResult.ok(List<BloodPressureRecord> result)=>
@@ -15,6 +11,10 @@ class RecordParsingResult {
/// Indicate a parsing failure.
factory RecordParsingResult.err(RecordParsingError error)=>
RecordParsingResult._create(null, error);
+ RecordParsingResult._create(this._result, this._error);
+
+ final List<BloodPressureRecord>? _result;
+ final RecordParsingError? _error;
/// Returns if there is an error present.
///
lib/model/storage/db/config_dao.dart
@@ -32,7 +32,7 @@ class ConfigDao {
ConfigDB.settingsTable,
columns: ['settings_json'],
where: 'profile_id = ?',
- whereArgs: [profileID]
+ whereArgs: [profileID],
);
late final Settings settings;
@@ -64,9 +64,9 @@ class ConfigDao {
ConfigDB.settingsTable,
{
'profile_id': profileID,
- 'settings_json': settings.toJson()
+ 'settings_json': settings.toJson(),
},
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@@ -83,7 +83,7 @@ class ConfigDao {
ConfigDB.exportSettingsTable,
columns: ['json'],
where: 'profile_id = ?',
- whereArgs: [profileID]
+ whereArgs: [profileID],
);
late final ExportSettings exportSettings;
@@ -115,9 +115,9 @@ class ConfigDao {
ConfigDB.exportSettingsTable,
{
'profile_id': profileID,
- 'json': settings.toJson()
+ 'json': settings.toJson(),
},
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@@ -135,7 +135,7 @@ class ConfigDao {
ConfigDB.exportCsvSettingsTable,
columns: ['json'],
where: 'profile_id = ?',
- whereArgs: [profileID]
+ whereArgs: [profileID],
);
late final CsvExportSettings exportSettings;
@@ -167,9 +167,9 @@ class ConfigDao {
ConfigDB.exportCsvSettingsTable,
{
'profile_id': profileID,
- 'json': settings.toJson()
+ 'json': settings.toJson(),
},
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@@ -187,7 +187,7 @@ class ConfigDao {
ConfigDB.exportPdfSettingsTable,
columns: ['json'],
where: 'profile_id = ?',
- whereArgs: [profileID]
+ whereArgs: [profileID],
);
late final PdfExportSettings exportSettings;
@@ -219,9 +219,9 @@ class ConfigDao {
ConfigDB.exportPdfSettingsTable,
{
'profile_id': profileID,
- 'json': settings.toJson()
+ 'json': settings.toJson(),
},
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@@ -244,7 +244,7 @@ class ConfigDao {
ConfigDB.selectedIntervallStorageTable,
columns: ['stepSize', 'start', 'end'],
where: 'profile_id = ? AND storage_id = ?',
- whereArgs: [profileID, storageID]
+ whereArgs: [profileID, storageID],
);
late final IntervallStorage intervallStorage;
if (dbEntry.isEmpty) {
@@ -275,7 +275,7 @@ class ConfigDao {
await _configDB.database.insert(
ConfigDB.selectedIntervallStorageTable,
columnValueMap,
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@@ -293,7 +293,7 @@ class ConfigDao {
ConfigDB.exportColumnsTable,
columns: ['json'],
where: 'profile_id = ?',
- whereArgs: [profileID]
+ whereArgs: [profileID],
);
late final ExportColumnsManager columnsManager;
@@ -325,9 +325,9 @@ class ConfigDao {
ConfigDB.exportColumnsTable,
{
'profile_id': profileID,
- 'json': manager.toJson()
+ 'json': manager.toJson(),
},
- conflictAlgorithm: ConflictAlgorithm.replace
+ conflictAlgorithm: ConflictAlgorithm.replace,
);
}
}
\ No newline at end of file
lib/model/storage/db/config_db.dart
@@ -1,7 +1,7 @@
import 'dart:async';
-import 'package:blood_pressure_app/model/storage/export_csv_settings_store.dart';
-import 'package:blood_pressure_app/model/storage/export_pdf_settings_store.dart';
+import 'package:blood_pressure_app/model/storage/export_columns_store.dart';
+import 'package:blood_pressure_app/model/storage/storage.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
lib/model/storage/convert_util.dart
@@ -10,14 +10,14 @@ import 'package:flutter/material.dart';
/// automatically and can be just checked with the `is boolean` condition, but the user may also write `"true"` or 1
/// which are equally valid but would not get converted automatically.
class ConvertUtil {
- static bool? parseBool(dynamic value) {
+ static bool? parseBool(value) {
if (value is bool) return value;
if (parseString(value)?.toLowerCase() == 'true' || parseInt(value) == 1) return true;
if (parseString(value)?.toLowerCase() == 'false' || parseInt(value) == 0) return false;
return null;
}
- static int? parseInt(dynamic value) {
+ static int? parseInt(value) {
if (value is int) return value;
if (value is double) return _isInt(value);
if (value is String) return int.tryParse(value) ?? _isInt(double.tryParse(value));
@@ -29,14 +29,14 @@ class ConvertUtil {
return null;
}
- static double? parseDouble(dynamic value) {
+ static double? parseDouble(value) {
if (value is double) return value;
if (value is int) return value.toDouble();
if (value is String) return double.tryParse(value);
return null;
}
- static String? parseString(dynamic value) {
+ static String? parseString(value) {
if (value is String) return value;
if (value is int || value is double || value is bool) return value.toString();
// No check for Object. While this would be convertible to string,
@@ -48,7 +48,7 @@ class ConvertUtil {
return value.languageCode;
}
- static Locale? parseLocale(dynamic value) {
+ static Locale? parseLocale(value) {
if (value is Locale) return value;
// Should not use parseString, as values that get caught by it can not be locales.
if (value is String && value.toLowerCase() == 'null') return null;
@@ -56,7 +56,7 @@ class ConvertUtil {
return null;
}
- static Color? parseColor(dynamic value) {
+ static Color? parseColor(value) {
if (value is MaterialColor || value is Color) return value;
if (value == null) return null;
@@ -66,21 +66,21 @@ class ConvertUtil {
return null;
}
- static DateTimeRange? parseRange(dynamic start, dynamic end) {
+ static DateTimeRange? parseRange(start, end) {
final startTimestamp = parseInt(start);
final endTimestamp = parseInt(end);
if (startTimestamp == null || endTimestamp == null) return null;
return DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(startTimestamp),
- end: DateTime.fromMillisecondsSinceEpoch(endTimestamp)
+ end: DateTime.fromMillisecondsSinceEpoch(endTimestamp),
);
}
/// Example usage: `ConvertUtil.parseList<String>(json['columns'])`
- static List<T>? parseList<T>(dynamic value) {
+ static List<T>? parseList<T>(value) {
if (value is List<T>) return value;
if (value is List<dynamic>) {
- List<T> validValues = [];
+ final List<T> validValues = [];
for (final v in value) {
if (v is T) validValues.add(v);
}
@@ -90,8 +90,8 @@ class ConvertUtil {
return null;
}
- static ThemeMode? parseThemeMode(dynamic value) {
- int? intValue = ConvertUtil.parseInt(value);
+ static ThemeMode? parseThemeMode(value) {
+ final int? intValue = ConvertUtil.parseInt(value);
switch(intValue) {
case null:
return null;
lib/model/storage/export_columns_store.dart
@@ -6,6 +6,33 @@ import 'package:flutter/material.dart';
/// Class for managing columns available to the user.
class ExportColumnsManager extends ChangeNotifier {
+
+ factory ExportColumnsManager.fromMap(Map<String, dynamic> map) {
+ final List<dynamic> jsonUserColumns = map['userColumns'];
+ final manager = ExportColumnsManager();
+ for (final Map<String, dynamic> c in jsonUserColumns) {
+ switch (c['t']) {
+ case 0:
+ manager.addOrUpdate(UserColumn.explicit(c['id'], c['csvTitle'], c['formatString']));
+ break;
+ case 1:
+ manager.addOrUpdate(TimeColumn.explicit(c['id'], c['csvTitle'], c['formatPattern']));
+ break;
+ default:
+ assert(false, 'Unexpected column type ${c['t']}.');
+ }
+ }
+ return manager;
+ }
+
+ factory ExportColumnsManager.fromJson(String jsonString) {
+ try {
+ return ExportColumnsManager.fromMap(jsonDecode(jsonString));
+ } catch (e) {
+ assert(e is FormatException || e is TypeError);
+ return ExportColumnsManager();
+ }
+ }
/// Create a new manager for export columns.
///
/// It will be filled with the default columns but won't contain initial user columns.
@@ -35,7 +62,7 @@ class ExportColumnsManager extends ChangeNotifier {
/// Calling this with the [ExportColumnI.internalIdentifier] of build-in columns
/// or undefined columns will have no effect.
void deleteUserColumn(String identifier) {
- assert(_userColumns.containsKey(identifier), 'Don\'t call deleteUserColumn for non-existent or non-user columns');
+ assert(_userColumns.containsKey(identifier), "Don't call deleteUserColumn for non-existent or non-user columns");
_userColumns.remove(identifier);
notifyListeners();
}
@@ -85,7 +112,7 @@ class ExportColumnsManager extends ChangeNotifier {
't': 0, // class type
'id': c.internalIdentifier,
'csvTitle': c.csvTitle,
- 'formatString': c.formatPattern
+ 'formatString': c.formatPattern,
});
break;
case BuildInColumn():
@@ -97,7 +124,7 @@ class ExportColumnsManager extends ChangeNotifier {
't': 1, // class type
'id': c.internalIdentifier,
'csvTitle': c.csvTitle,
- 'formatPattern': c.formatPattern
+ 'formatPattern': c.formatPattern,
});
break;
}
@@ -108,32 +135,5 @@ class ExportColumnsManager extends ChangeNotifier {
}
String toJson() => jsonEncode(toMap());
-
- factory ExportColumnsManager.fromMap(Map<String, dynamic> map) {
- final List<dynamic> jsonUserColumns = map['userColumns'];
- final manager = ExportColumnsManager();
- for (final Map<String, dynamic> c in jsonUserColumns) {
- switch (c['t']) {
- case 0:
- manager.addOrUpdate(UserColumn.explicit(c['id'], c['csvTitle'], c['formatString']));
- break;
- case 1:
- manager.addOrUpdate(TimeColumn.explicit(c['id'], c['csvTitle'], c['formatPattern']));
- break;
- default:
- assert(false, 'Unexpected column type ${c['t']}.');
- }
- }
- return manager;
- }
-
- factory ExportColumnsManager.fromJson(String jsonString) {
- try {
- return ExportColumnsManager.fromMap(jsonDecode(jsonString));
- } catch (e) {
- assert(e is FormatException || e is TypeError);
- return ExportColumnsManager();
- }
- }
}
lib/model/storage/export_csv_settings_store.dart
@@ -18,7 +18,7 @@ class CsvExportSettings extends ChangeNotifier implements CustomFieldsSettings {
if (exportHeadline != null) _exportHeadline = exportHeadline;
if (exportFieldsConfiguration != null) _exportFieldsConfiguration = exportFieldsConfiguration;
- _exportFieldsConfiguration.addListener(() => notifyListeners());
+ _exportFieldsConfiguration.addListener(notifyListeners);
}
factory CsvExportSettings.fromMap(Map<String, dynamic> map) {
@@ -56,7 +56,7 @@ class CsvExportSettings extends ChangeNotifier implements CustomFieldsSettings {
'fieldDelimiter': fieldDelimiter,
'textDelimiter': textDelimiter,
'exportHeadline': exportHeadline,
- 'exportFieldsConfiguration': exportFieldsConfiguration.toJson()
+ 'exportFieldsConfiguration': exportFieldsConfiguration.toJson(),
};
String toJson() => jsonEncode(toMap());
lib/model/storage/export_pdf_settings_store.dart
@@ -26,7 +26,7 @@ class PdfExportSettings extends ChangeNotifier implements CustomFieldsSettings {
if (cellFontSize != null) _cellFontSize = cellFontSize;
if (exportFieldsConfiguration != null) _exportFieldsConfiguration = exportFieldsConfiguration;
- _exportFieldsConfiguration.addListener(() => notifyListeners());
+ _exportFieldsConfiguration.addListener(notifyListeners);
}
factory PdfExportSettings.fromMap(Map<String, dynamic> map) => PdfExportSettings(
@@ -58,7 +58,7 @@ class PdfExportSettings extends ChangeNotifier implements CustomFieldsSettings {
'cellHeight': cellHeight,
'headerFontSize': headerFontSize,
'cellFontSize': cellFontSize,
- 'exportFieldsConfiguration': exportFieldsConfiguration.toJson()
+ 'exportFieldsConfiguration': exportFieldsConfiguration.toJson(),
};
String toJson() => jsonEncode(toMap());
lib/model/storage/export_settings_store.dart
@@ -8,7 +8,7 @@ class ExportSettings extends ChangeNotifier {
ExportSettings({
ExportFormat? exportFormat,
String? defaultExportDir,
- bool? exportAfterEveryEntry
+ bool? exportAfterEveryEntry,
}) {
if (exportFormat != null) _exportFormat = exportFormat;
if (defaultExportDir != null) _defaultExportDir = defaultExportDir;
@@ -18,7 +18,7 @@ class ExportSettings extends ChangeNotifier {
factory ExportSettings.fromMap(Map<String, dynamic> map) => ExportSettings(
exportFormat: ExportFormat.deserialize(map['exportFormat']),
defaultExportDir: ConvertUtil.parseString(map['defaultExportDir']),
- exportAfterEveryEntry: ConvertUtil.parseBool(map['exportAfterEveryEntry'])
+ exportAfterEveryEntry: ConvertUtil.parseBool(map['exportAfterEveryEntry']),
);
factory ExportSettings.fromJson(String json) {
@@ -32,7 +32,7 @@ class ExportSettings extends ChangeNotifier {
Map<String, dynamic> toMap() => <String, dynamic>{
'exportFormat': exportFormat.serialize(),
'defaultExportDir': defaultExportDir,
- 'exportAfterEveryEntry': exportAfterEveryEntry
+ 'exportAfterEveryEntry': exportAfterEveryEntry,
};
String toJson() => jsonEncode(toMap());
@@ -77,8 +77,8 @@ enum ExportFormat {
}
}
- factory ExportFormat.deserialize(dynamic value) {
- int? intValue = ConvertUtil.parseInt(value);
+ factory ExportFormat.deserialize(value) {
+ final int? intValue = ConvertUtil.parseInt(value);
if (value == null || intValue == null) return ExportFormat.csv;
switch(intValue) {
lib/model/storage/intervall_store.dart
@@ -7,12 +7,6 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart';
/// Class for storing the current interval, as it is needed in start page, statistics and export.
class IntervallStorage extends ChangeNotifier {
- IntervallStorage({TimeStep? stepSize, DateTimeRange? range}) {
- _stepSize = stepSize ?? TimeStep.last7Days;
- _currentRange = range ?? _getMostRecentDisplayIntervall();
- }
- late TimeStep _stepSize;
- late DateTimeRange _currentRange;
factory IntervallStorage.fromMap(Map<String, dynamic> map) => IntervallStorage(
stepSize: TimeStep.deserialize(map['stepSize']),
@@ -26,6 +20,12 @@ class IntervallStorage extends ChangeNotifier {
return IntervallStorage();
}
}
+ IntervallStorage({TimeStep? stepSize, DateTimeRange? range}) {
+ _stepSize = stepSize ?? TimeStep.last7Days;
+ _currentRange = range ?? _getMostRecentDisplayIntervall();
+ }
+ late TimeStep _stepSize;
+ late DateTimeRange _currentRange;
Map<String, dynamic> toMap() => <String, dynamic>{
'stepSize': stepSize.serialize(),
@@ -44,9 +44,7 @@ class IntervallStorage extends ChangeNotifier {
setToMostRecentIntervall();
}
- DateTimeRange get currentRange {
- return _currentRange;
- }
+ DateTimeRange get currentRange => _currentRange;
set currentRange(DateTimeRange value) {
_currentRange = value;
@@ -66,45 +64,45 @@ class IntervallStorage extends ChangeNotifier {
case TimeStep.day:
currentRange = DateTimeRange(
start: oldStart.copyWith(day: oldStart.day + directionalStep),
- end: oldEnd.copyWith(day: oldEnd.day + directionalStep)
+ end: oldEnd.copyWith(day: oldEnd.day + directionalStep),
);
break;
case TimeStep.week:
case TimeStep.last7Days:
currentRange = DateTimeRange(
start: oldStart.copyWith(day: oldStart.day + directionalStep * 7),
- end: oldEnd.copyWith(day: oldEnd.day + directionalStep * 7)
+ end: oldEnd.copyWith(day: oldEnd.day + directionalStep * 7),
);
break;
case TimeStep.month:
currentRange = DateTimeRange(
start: oldStart.copyWith(month: oldStart.month + directionalStep),
- end: oldEnd.copyWith(month: oldEnd.month + directionalStep)
+ end: oldEnd.copyWith(month: oldEnd.month + directionalStep),
);
break;
case TimeStep.year:
currentRange = DateTimeRange(
start: oldStart.copyWith(year: oldStart.year + directionalStep),
- end: oldEnd.copyWith(year: oldEnd.year + directionalStep)
+ end: oldEnd.copyWith(year: oldEnd.year + directionalStep),
);
break;
case TimeStep.lifetime:
currentRange = DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(1),
- end: DateTime.now().copyWith(hour: 23, minute: 59, second: 59)
+ end: DateTime.now().copyWith(hour: 23, minute: 59, second: 59),
);
break;
case TimeStep.last30Days:
currentRange = DateTimeRange(
start: oldStart.copyWith(day: oldStart.day + directionalStep * 30),
- end: oldEnd.copyWith(day: oldEnd.day + directionalStep * 30)
+ end: oldEnd.copyWith(day: oldEnd.day + directionalStep * 30),
);
break;
case TimeStep.custom:
final step = oldEnd.difference(oldStart) * directionalStep;
currentRange = DateTimeRange(
start: oldStart.add(step),
- end: oldEnd.add(step)
+ end: oldEnd.add(step),
);
break;
}
@@ -140,7 +138,7 @@ class IntervallStorage extends ChangeNotifier {
case TimeStep.custom:
return DateTimeRange(
start: now.subtract(currentRange.duration),
- end: now
+ end: now,
);
}
}
@@ -201,8 +199,8 @@ enum TimeStep {
}
}
- factory TimeStep.deserialize(dynamic value) {
- int? intValue = ConvertUtil.parseInt(value);
+ factory TimeStep.deserialize(value) {
+ final int? intValue = ConvertUtil.parseInt(value);
if (intValue == null) return TimeStep.last7Days;
switch (intValue) {
lib/model/storage/settings_store.dart
@@ -68,7 +68,7 @@ class Settings extends ChangeNotifier {
}
factory Settings.fromMap(Map<String, dynamic> map) {
- var settingsObject = Settings(
+ final settingsObject = Settings(
accentColor: ConvertUtil.parseColor(map['accentColor']),
sysColor: ConvertUtil.parseColor(map['sysColor']),
diaColor: ConvertUtil.parseColor(map['diaColor']),
@@ -88,12 +88,12 @@ class Settings extends ChangeNotifier {
useLegacyList: ConvertUtil.parseBool(map['useLegacyList']),
language: ConvertUtil.parseLocale(map['language']),
horizontalGraphLines: ConvertUtil.parseList<String>(map['horizontalGraphLines'])?.map((e) =>
- HorizontalGraphLine.fromJson(jsonDecode(e))).toList(),
+ HorizontalGraphLine.fromJson(jsonDecode(e)),).toList(),
needlePinBarWidth: ConvertUtil.parseDouble(map['needlePinBarWidth']),
lastVersion: ConvertUtil.parseInt(map['lastVersion']),
bottomAppBars: ConvertUtil.parseBool(map['bottomAppBars']),
medications: ConvertUtil.parseList<String>(map['medications'])?.map((e) =>
- Medicine.fromJson(jsonDecode(e))).toList(),
+ Medicine.fromJson(jsonDecode(e)),).toList(),
highestMedIndex: ConvertUtil.parseInt(map['highestMedIndex']),
);
@@ -131,11 +131,11 @@ class Settings extends ChangeNotifier {
'startWithAddMeasurementPage': startWithAddMeasurementPage,
'useLegacyList': useLegacyList,
'language': ConvertUtil.serializeLocale(language),
- 'horizontalGraphLines': horizontalGraphLines.map((e) => jsonEncode(e)).toList(),
+ 'horizontalGraphLines': horizontalGraphLines.map(jsonEncode).toList(),
'needlePinBarWidth': _needlePinBarWidth,
'lastVersion': lastVersion,
'bottomAppBars': bottomAppBars,
- 'medications': medications.map((e) => jsonEncode(e)).toList(),
+ 'medications': medications.map(jsonEncode).toList(),
'highestMedIndex': highestMedIndex,
};
lib/model/storage/update_legacy_settings.dart
@@ -19,10 +19,10 @@ import 'package:sqflite/sqflite.dart';
/// Function for upgrading shared preferences from pre 1.5.5 versions.
Future<void> updateLegacySettings(Settings settings, ExportSettings exportSettings, CsvExportSettings csvExportSettings,
- PdfExportSettings pdfExportSettings, IntervallStoreManager intervallStoreManager) async {
- SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
+ PdfExportSettings pdfExportSettings, IntervallStoreManager intervallStoreManager,) async {
+ final SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
- List<Future> futures = [];
+ final List<Future> futures = [];
final keys = sharedPreferences.getKeys();
for (final key in keys) { // remove these first
@@ -178,7 +178,7 @@ Future<void> updateLegacySettings(Settings settings, ExportSettings exportSettin
break;
case 'horizontalGraphLines':
settings.horizontalGraphLines = sharedPreferences.getStringList(key)!.map((e) =>
- HorizontalGraphLine.fromJson(jsonDecode(e))).toList();
+ HorizontalGraphLine.fromJson(jsonDecode(e)),).toList();
break;
case 'useLegacyList':
settings.useLegacyList = sharedPreferences.getBool(key)!;
@@ -203,13 +203,13 @@ Future<void> updateLegacyExport(ConfigDB database, ExportColumnsManager manager)
if (await _tableExists(database.database, ConfigDB.exportStringsTable)) {
final existingDbEntries = await database.database.query(
ConfigDB.exportStringsTable,
- columns: ['internalColumnName', 'columnTitle', 'formatPattern']
+ columns: ['internalColumnName', 'columnTitle', 'formatPattern'],
);
for (final e in existingDbEntries) {
final column = UserColumn(
e['internalColumnName'].toString(),
e['columnTitle'].toString(),
- e['formatPattern'].toString()
+ e['formatPattern'].toString(),
);
if (column.formatPattern?.contains(r'$FORMAT') ?? false) {
Fluttertoast.showToast(
@@ -219,9 +219,9 @@ Future<void> updateLegacyExport(ConfigDB database, ExportColumnsManager manager)
manager.addOrUpdate(column);
}
- await database.database.execute("DROP TABLE IF EXISTS ${ConfigDB.exportStringsTable};");
+ await database.database.execute('DROP TABLE IF EXISTS ${ConfigDB.exportStringsTable};');
}
}
Future<bool> _tableExists(Database database, String tableName) async => (await database.rawQuery(
- "SELECT name FROM sqlite_master WHERE type='table' AND name='$tableName';")).isNotEmpty;
\ No newline at end of file
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='$tableName';",)).isNotEmpty;
\ No newline at end of file
lib/model/blood_pressure_analyzer.dart
@@ -4,9 +4,9 @@ import 'package:blood_pressure_app/model/blood_pressure/record.dart';
import 'package:collection/collection.dart';
class BloodPressureAnalyser {
- final List<BloodPressureRecord> _records;
BloodPressureAnalyser(this._records);
+ final List<BloodPressureRecord> _records;
int get count => _records.length;
@@ -76,9 +76,9 @@ class BloodPressureAnalyser {
/// inner list index is hour of day ([0] -> 00:00-00:59; [1] -> ...)
List<List<int>> get allAvgsRelativeToDaytime {
// setup vars
- List<List<int>> allDiaValuesRelativeToTime = [];
- List<List<int>> allSysValuesRelativeToTime = [];
- List<List<int>> allPulValuesRelativeToTime = [];
+ final List<List<int>> allDiaValuesRelativeToTime = [];
+ final List<List<int>> allSysValuesRelativeToTime = [];
+ final List<List<int>> allPulValuesRelativeToTime = [];
for (int i = 0; i < 24; i++) {
allDiaValuesRelativeToTime.add([]);
allSysValuesRelativeToTime.add([]);
@@ -87,8 +87,8 @@ class BloodPressureAnalyser {
// sort all data
final dbRes = _records;
- for (var e in dbRes) {
- DateTime ts = DateTime.fromMillisecondsSinceEpoch(e.creationTime.millisecondsSinceEpoch);
+ for (final e in dbRes) {
+ final DateTime ts = DateTime.fromMillisecondsSinceEpoch(e.creationTime.millisecondsSinceEpoch);
if (e.diastolic != null) allDiaValuesRelativeToTime[ts.hour].add(e.diastolic!);
if (e.systolic != null)allSysValuesRelativeToTime[ts.hour].add(e.systolic!);
if (e.pulse != null)allPulValuesRelativeToTime[ts.hour].add(e.pulse!);
@@ -106,7 +106,7 @@ class BloodPressureAnalyser {
}
// make avgs
- List<List<int>> res = [[], [], []];
+ final List<List<int>> res = [[], [], []];
for (int i = 0; i < 24; i++) {
res[0].add(allDiaValuesRelativeToTime[i].average.toInt());
res[1].add(allSysValuesRelativeToTime[i].average.toInt());
lib/model/horizontal_graph_line.dart
@@ -1,6 +1,11 @@
+import 'package:blood_pressure_app/model/blood_pressure/record.dart';
import 'package:flutter/material.dart';
class HorizontalGraphLine {
+
+ HorizontalGraphLine.fromJson(Map<String, dynamic> json)
+ : color = Color(json['color']),
+ height = json['height'];
HorizontalGraphLine(this.color, this.height);
/// Color of the line.
@@ -11,10 +16,6 @@ class HorizontalGraphLine {
/// Usually on the same scale as [BloodPressureRecord]
int height;
- HorizontalGraphLine.fromJson(Map<String, dynamic> json)
- : color = Color(json['color']),
- height = json['height'];
-
Map<String, dynamic> toJson() => {
'color': color.value,
'height': height,
lib/model/iso_lang_names.dart
@@ -1,190 +1,188 @@
import 'package:flutter/material.dart';
final _isoLangs = {
- "ab": "аҧсуа",
- "aa": "Afaraf",
- "af": "Afrikaans",
- "ak": "Akan",
- "sq": "Shqip",
- "am": "አማርኛ",
- "ar": "العربية",
- "an": "Aragonés",
- "hy": "Հայերեն",
- "as": "অসমীয়া",
- "av": "авар мацӀ, магӀарул мацӀ",
- "ae": "avesta",
- "ay": "aymar aru",
- "az": "azərbaycan dili",
- "bm": "bamanankan",
- "ba": "башҡорт теле",
- "eu": "euskara, euskera",
- "be": "Беларуская",
- "bn": "বাংলা",
- "bh": "भोजपुरी",
- "bi": "Bislama",
- "bs": "bosanski jezik",
- "br": "brezhoneg",
- "bg": "български език",
- "my": "ဗမာစာ",
- "ca": "Català",
- "ch": "Chamoru",
- "ce": "нохчийн мотт",
- "ny": "chiCheŵa, chinyanja",
- "zh": "中文 (Zhōngwén)",
- "cv": "чӑваш чӗлхи",
- "kw": "Kernewek",
- "co": "corsu, lingua corsa",
- "cr": "ᓀᐦᐃᔭᐍᐏᐣ",
- "hr": "hrvatski",
- "cs": "česky, čeština",
- "da": "dansk",
- "dv": "ދިވެހި",
- "nl": "Nederlands, Vlaams",
- "en": "English",
- "eo": "Esperanto",
- "et": "eesti, eesti keel",
- "ee": "Eʋegbe",
- "fo": "føroyskt",
- "fj": "vosa Vakaviti",
- "fi": "suomi, suomen kieli",
- "fr": "française",
- "ff": "Fulfulde, Pulaar, Pular",
- "gl": "Galego",
- "ka": "ქართული",
- "de": "Deutsch",
- "el": "Ελληνικά",
- "gn": "Avañeẽ",
- "gu": "ગુજરાતી",
- "ht": "Kreyòl ayisyen",
- "ha": "Hausa, هَوُسَ",
- "he": "עברית",
- "hz": "Otjiherero",
- "hi": "हिन्दी, हिंदी",
- "ho": "Hiri Motu",
- "hu": "Magyar",
- "ia": "Interlingua",
- "id": "Bahasa Indonesia",
- "ie": "Occidental (Interlingue)",
- "ga": "Gaeilge",
- "ig": "Asụsụ Igbo",
- "ik": "Iñupiaq, Iñupiatun",
- "io": "Ido",
- "is": "Íslenska",
- "it": "Italiano",
- "iu": "ᐃᓄᒃᑎᑐᑦ",
- "ja": "日本語 (にほんご/にっぽんご)",
- "jv": "basa Jawa",
- "kl": "kalaallisut, kalaallit oqaasii",
- "kn": "ಕನ್ನಡ",
- "kr": "Kanuri",
- "ks": "कश्मीरी, كشميري",
- "kk": "Қазақ тілі",
- "km": "ភាសាខ្មែរ",
- "ki": "Gĩkũyũ",
- "rw": "Ikinyarwanda",
- "ky": "кыргыз тили",
- "kv": "коми кыв",
- "kg": "KiKongo",
- "ko": "한국어 (韓國語), 조선말 (朝鮮語)",
- "ku": "Kurdî, كوردی",
- "kj": "Kuanyama",
- "la": "latine, lingua latina",
- "lb": "Lëtzebuergesch",
- "lg": "Luganda",
- "li": "Limburgs",
- "ln": "Lingála",
- "lo": "ພາສາລາວ",
- "lt": "lietuvių kalba",
- "lu": "",
- "lv": "latviešu valoda",
- "gv": "Gaelg, Gailck",
- "mk": "македонски јазик",
- "mg": "Malagasy fiteny",
- "ms": "bahasa Melayu, بهاس ملايو",
- "ml": "മലയാളം",
- "mt": "Malti",
- "mi": "te reo Māori",
- "mr": "मराठी",
- "mh": "Kajin M̧ajeļ",
- "mn": "монгол",
- "na": "Ekakairũ Naoero",
- "nv": "Diné bizaad, Dinékʼehǰí",
- "nb": "Norsk bokmål",
- "nd": "isiNdebele",
- "ne": "नेपाली",
- "ng": "Owambo",
- "nn": "Norsk nynorsk",
- "no": "Norsk",
- "ii": "ꆈꌠ꒿ Nuosuhxop",
- "nr": "isiNdebele",
- "oc": "Occitan",
- "oj": "ᐊᓂᔑᓈᐯᒧᐎᓐ",
- "cu": "ѩзыкъ словѣньскъ",
- "om": "Afaan Oromoo",
- "or": "ଓଡ଼ିଆ",
- "os": "ирон æвзаг",
- "pa": "ਪੰਜਾਬੀ, پنجابی",
- "pi": "पाऴि",
- "fa": "فارسی",
- "pl": "polski",
- "ps": "پښتو",
- "pt": "Português",
- "qu": "Runa Simi, Kichwa",
- "rm": "rumantsch grischun",
- "rn": "kiRundi",
- "ro": "română",
- "ru": "русский язык",
- "sa": "संस्कृतम्",
- "sc": "sardu",
- "sd": "सिन्धी, سنڌي، سندھی",
- "se": "Davvisámegiella",
- "sm": "gagana faa Samoa",
- "sg": "yângâ tî sängö",
- "sr": "српски језик",
- "gd": "Gàidhlig",
- "sn": "chiShona",
- "si": "සිංහල",
- "sk": "slovenčina",
- "sl": "slovenščina",
- "so": "Soomaaliga, af Soomaali",
- "st": "Sesotho",
- "es": "español, castellano",
- "su": "Basa Sunda",
- "sw": "Kiswahili",
- "ss": "SiSwati",
- "sv": "svenska",
- "ta": "தமிழ்",
- "te": "తెలుగు",
- "tg": "тоҷикӣ, toğikī, تاجیکی",
- "th": "ไทย",
- "ti": "ትግርኛ",
- "bo": "བོད་ཡིག",
- "tk": "Türkmen, Түркмен",
- "tl": "Wikang Tagalog, ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔",
- "tn": "Setswana",
- "to": "faka Tonga",
- "tr": "Türkçe",
- "ts": "Xitsonga",
- "tt": "татарча, tatarça, تاتارچا",
- "tw": "Twi",
- "ty": "Reo Tahiti",
- "ug": "Uyƣurqə, ئۇيغۇرچە",
- "uk": "українська",
- "ur": "اردو",
- "uz": "zbek, Ўзбек, أۇزبېك",
- "ve": "Tshivenḓa",
- "vi": "Tiếng Việt",
- "vo": "Volapük",
- "wa": "Walon",
- "cy": "Cymraeg",
- "wo": "Wollof",
- "fy": "Frysk",
- "xh": "isiXhosa",
- "yi": "ייִדיש",
- "yo": "Yorùbá",
- "za": "Saɯ cueŋƅ, Saw cuengh"
+ 'ab': 'аҧсуа',
+ 'aa': 'Afaraf',
+ 'af': 'Afrikaans',
+ 'ak': 'Akan',
+ 'sq': 'Shqip',
+ 'am': 'አማርኛ',
+ 'ar': 'العربية',
+ 'an': 'Aragonés',
+ 'hy': 'Հայերեն',
+ 'as': 'অসমীয়া',
+ 'av': 'авар мацӀ, магӀарул мацӀ',
+ 'ae': 'avesta',
+ 'ay': 'aymar aru',
+ 'az': 'azərbaycan dili',
+ 'bm': 'bamanankan',
+ 'ba': 'башҡорт теле',
+ 'eu': 'euskara, euskera',
+ 'be': 'Беларуская',
+ 'bn': 'বাংলা',
+ 'bh': 'भोजपुरी',
+ 'bi': 'Bislama',
+ 'bs': 'bosanski jezik',
+ 'br': 'brezhoneg',
+ 'bg': 'български език',
+ 'my': 'ဗမာစာ',
+ 'ca': 'Català',
+ 'ch': 'Chamoru',
+ 'ce': 'нохчийн мотт',
+ 'ny': 'chiCheŵa, chinyanja',
+ 'zh': '中文 (Zhōngwén)',
+ 'cv': 'чӑваш чӗлхи',
+ 'kw': 'Kernewek',
+ 'co': 'corsu, lingua corsa',
+ 'cr': 'ᓀᐦᐃᔭᐍᐏᐣ',
+ 'hr': 'hrvatski',
+ 'cs': 'česky, čeština',
+ 'da': 'dansk',
+ 'dv': 'ދިވެހި',
+ 'nl': 'Nederlands, Vlaams',
+ 'en': 'English',
+ 'eo': 'Esperanto',
+ 'et': 'eesti, eesti keel',
+ 'ee': 'Eʋegbe',
+ 'fo': 'føroyskt',
+ 'fj': 'vosa Vakaviti',
+ 'fi': 'suomi, suomen kieli',
+ 'fr': 'française',
+ 'ff': 'Fulfulde, Pulaar, Pular',
+ 'gl': 'Galego',
+ 'ka': 'ქართული',
+ 'de': 'Deutsch',
+ 'el': 'Ελληνικά',
+ 'gn': 'Avañeẽ',
+ 'gu': 'ગુજરાતી',
+ 'ht': 'Kreyòl ayisyen',
+ 'ha': 'Hausa, هَوُسَ',
+ 'he': 'עברית',
+ 'hz': 'Otjiherero',
+ 'hi': 'हिन्दी, हिंदी',
+ 'ho': 'Hiri Motu',
+ 'hu': 'Magyar',
+ 'ia': 'Interlingua',
+ 'id': 'Bahasa Indonesia',
+ 'ie': 'Occidental (Interlingue)',
+ 'ga': 'Gaeilge',
+ 'ig': 'Asụsụ Igbo',
+ 'ik': 'Iñupiaq, Iñupiatun',
+ 'io': 'Ido',
+ 'is': 'Íslenska',
+ 'it': 'Italiano',
+ 'iu': 'ᐃᓄᒃᑎᑐᑦ',
+ 'ja': '日本語 (にほんご/にっぽんご)',
+ 'jv': 'basa Jawa',
+ 'kl': 'kalaallisut, kalaallit oqaasii',
+ 'kn': 'ಕನ್ನಡ',
+ 'kr': 'Kanuri',
+ 'ks': 'कश्मीरी, كشميري',
+ 'kk': 'Қазақ тілі',
+ 'km': 'ភាសាខ្មែរ',
+ 'ki': 'Gĩkũyũ',
+ 'rw': 'Ikinyarwanda',
+ 'ky': 'кыргыз тили',
+ 'kv': 'коми кыв',
+ 'kg': 'KiKongo',
+ 'ko': '한국어 (韓國語), 조선말 (朝鮮語)',
+ 'ku': 'Kurdî, كوردی',
+ 'kj': 'Kuanyama',
+ 'la': 'latine, lingua latina',
+ 'lb': 'Lëtzebuergesch',
+ 'lg': 'Luganda',
+ 'li': 'Limburgs',
+ 'ln': 'Lingála',
+ 'lo': 'ພາສາລາວ',
+ 'lt': 'lietuvių kalba',
+ 'lu': '',
+ 'lv': 'latviešu valoda',
+ 'gv': 'Gaelg, Gailck',
+ 'mk': 'македонски јазик',
+ 'mg': 'Malagasy fiteny',
+ 'ms': 'bahasa Melayu, بهاس ملايو',
+ 'ml': 'മലയാളം',
+ 'mt': 'Malti',
+ 'mi': 'te reo Māori',
+ 'mr': 'मराठी',
+ 'mh': 'Kajin M̧ajeļ',
+ 'mn': 'монгол',
+ 'na': 'Ekakairũ Naoero',
+ 'nv': 'Diné bizaad, Dinékʼehǰí',
+ 'nb': 'Norsk bokmål',
+ 'nd': 'isiNdebele',
+ 'ne': 'नेपाली',
+ 'ng': 'Owambo',
+ 'nn': 'Norsk nynorsk',
+ 'no': 'Norsk',
+ 'ii': 'ꆈꌠ꒿ Nuosuhxop',
+ 'nr': 'isiNdebele',
+ 'oc': 'Occitan',
+ 'oj': 'ᐊᓂᔑᓈᐯᒧᐎᓐ',
+ 'cu': 'ѩзыкъ словѣньскъ',
+ 'om': 'Afaan Oromoo',
+ 'or': 'ଓଡ଼ିଆ',
+ 'os': 'ирон æвзаг',
+ 'pa': 'ਪੰਜਾਬੀ, پنجابی',
+ 'pi': 'पाऴि',
+ 'fa': 'فارسی',
+ 'pl': 'polski',
+ 'ps': 'پښتو',
+ 'pt': 'Português',
+ 'qu': 'Runa Simi, Kichwa',
+ 'rm': 'rumantsch grischun',
+ 'rn': 'kiRundi',
+ 'ro': 'română',
+ 'ru': 'русский язык',
+ 'sa': 'संस्कृतम्',
+ 'sc': 'sardu',
+ 'sd': 'सिन्धी, سنڌي، سندھی',
+ 'se': 'Davvisámegiella',
+ 'sm': 'gagana faa Samoa',
+ 'sg': 'yângâ tî sängö',
+ 'sr': 'српски језик',
+ 'gd': 'Gàidhlig',
+ 'sn': 'chiShona',
+ 'si': 'සිංහල',
+ 'sk': 'slovenčina',
+ 'sl': 'slovenščina',
+ 'so': 'Soomaaliga, af Soomaali',
+ 'st': 'Sesotho',
+ 'es': 'español, castellano',
+ 'su': 'Basa Sunda',
+ 'sw': 'Kiswahili',
+ 'ss': 'SiSwati',
+ 'sv': 'svenska',
+ 'ta': 'தமிழ்',
+ 'te': 'తెలుగు',
+ 'tg': 'тоҷикӣ, toğikī, تاجیکی',
+ 'th': 'ไทย',
+ 'ti': 'ትግርኛ',
+ 'bo': 'བོད་ཡིག',
+ 'tk': 'Türkmen, Түркмен',
+ 'tl': 'Wikang Tagalog, ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔',
+ 'tn': 'Setswana',
+ 'to': 'faka Tonga',
+ 'tr': 'Türkçe',
+ 'ts': 'Xitsonga',
+ 'tt': 'татарча, tatarça, تاتارچا',
+ 'tw': 'Twi',
+ 'ty': 'Reo Tahiti',
+ 'ug': 'Uyƣurqə, ئۇيغۇرچە',
+ 'uk': 'українська',
+ 'ur': 'اردو',
+ 'uz': 'zbek, Ўзбек, أۇزبېك',
+ 've': 'Tshivenḓa',
+ 'vi': 'Tiếng Việt',
+ 'vo': 'Volapük',
+ 'wa': 'Walon',
+ 'cy': 'Cymraeg',
+ 'wo': 'Wollof',
+ 'fy': 'Frysk',
+ 'xh': 'isiXhosa',
+ 'yi': 'ייִדיש',
+ 'yo': 'Yorùbá',
+ 'za': 'Saɯ cueŋƅ, Saw cuengh',
};
-String? getDisplayLanguage(Locale l) {
- return _isoLangs[l.languageCode];
-}
+String? getDisplayLanguage(Locale l) => _isoLangs[l.languageCode];
lib/platform_integration/platform_client.dart
@@ -10,10 +10,10 @@ import 'package:flutter/services.dart';
/// - Add method name and arguments as a condition to the `onMethodCall` in the same class.
/// - Implement a helper function to this class that calls uses the platform channel (like [shareFile]).
class PlatformClient {
- /// Platform channel for sharing files, loading files, saving files and asking for directory permissions.
- static const _platformChannel = MethodChannel('bloodPressureApp.derdilla.com/storage');
PlatformClient._create();
+ /// Platform channel for sharing files, loading files, saving files and asking for directory permissions.
+ static const _platformChannel = MethodChannel('bloodPressureApp.derdilla.com/storage');
/// Share a file from application storage.
///
@@ -32,7 +32,7 @@ class PlatformClient {
await _platformChannel.invokeMethod('shareFile', {
'path': path,
'mimeType': mimeType,
- 'name': name
+ 'name': name,
});
return true;
} on PlatformException {
@@ -58,7 +58,7 @@ class PlatformClient {
await _platformChannel.invokeMethod('shareData', {
'data': data,
'mimeType': mimeType,
- 'name': name
+ 'name': name,
});
return true;
} on PlatformException {
lib/screens/elements/blood_pressure_builder.dart
@@ -15,8 +15,7 @@ class BloodPressureBuilder extends StatelessWidget {
final IntervallStoreManagerLocation rangeType;
@override
- Widget build(BuildContext context) {
- return Consumer<BloodPressureModel>(
+ Widget build(BuildContext context) => Consumer<BloodPressureModel>(
builder: (context, model, child) =>
Consumer<IntervallStoreManager>(
builder: (context, intervallManager, child) {
@@ -25,9 +24,8 @@ class BloodPressureBuilder extends StatelessWidget {
future: model.getInTimeRange(range.start, range.end),
onData: onData,
);
- }
- )
+ },
+ ),
);
- }
}
lib/screens/elements/display_interval_picker.dart
@@ -10,8 +10,7 @@ class IntervalPicker extends StatelessWidget {
final IntervallStoreManagerLocation type;
@override
- Widget build(BuildContext context) {
- return Consumer<IntervallStoreManager>(builder: (context, intervallStoreManager, child) {
+ Widget build(BuildContext context) => Consumer<IntervallStoreManager>(builder: (context, intervallStoreManager, child) {
final intervall = intervallStoreManager.get(type);
final String intervallDisplayText;
switch (intervall.stepSize) {
@@ -19,7 +18,7 @@ class IntervalPicker extends StatelessWidget {
intervallDisplayText = DateFormat.yMMMd(AppLocalizations.of(context)!.localeName).format(intervall.currentRange.start);
break;
case TimeStep.week:
- final dayOfYear = int.parse(DateFormat("D").format(intervall.currentRange.start));
+ final dayOfYear = int.parse(DateFormat('D').format(intervall.currentRange.start));
final weekOfYear = ((dayOfYear - intervall.currentRange.start.weekday + 10) / 7).floor();
intervallDisplayText = AppLocalizations.of(context)!.weekOfYear(weekOfYear, intervall.currentRange.start.year);
break;
@@ -68,7 +67,7 @@ class IntervalPicker extends StatelessWidget {
final res = await showDateRangePicker(
context: context,
firstDate: DateTime.fromMillisecondsSinceEpoch(1),
- lastDate: DateTime.now());
+ lastDate: DateTime.now(),);
if (res != null) {
intervall.changeStepSize(value!);
intervall.currentRange = res;
@@ -77,9 +76,7 @@ class IntervalPicker extends StatelessWidget {
intervall.changeStepSize(value);
}
},
- items: TimeStep.options.map<DropdownMenuItem<TimeStep>>((v) {
- return DropdownMenuItem(value: v, child: Text(v.getName(AppLocalizations.of(context)!)));
- }).toList(),
+ items: TimeStep.options.map<DropdownMenuItem<TimeStep>>((v) => DropdownMenuItem(value: v, child: Text(v.getName(AppLocalizations.of(context)!)))).toList(),
),
),
Expanded(
@@ -94,9 +91,8 @@ class IntervalPicker extends StatelessWidget {
),
),
),
- ]),
+ ],),
],
);
- });
- }
+ },);
}
lib/screens/elements/legacy_measurement_list.dart
@@ -12,8 +12,6 @@ import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class LegacyMeasurementsList extends StatelessWidget {
- late final List<int> _tableElementsSizes;
- late final int _sideFlex;
LegacyMeasurementsList(BuildContext context, {super.key}) {
if (MediaQuery.of(context).size.width < 1000) {
@@ -24,10 +22,11 @@ class LegacyMeasurementsList extends StatelessWidget {
_sideFlex = 5;
}
}
+ late final List<int> _tableElementsSizes;
+ late final int _sideFlex;
@override
- Widget build(BuildContext context) {
- return Consumer<Settings>(builder: (context, settings, child) =>
+ Widget build(BuildContext context) => Consumer<Settings>(builder: (context, settings, child) =>
Column(
children: [
Row(
@@ -38,19 +37,19 @@ class LegacyMeasurementsList extends StatelessWidget {
),
Expanded(
flex: _tableElementsSizes[0],
- child: Text(AppLocalizations.of(context)!.time, style: const TextStyle(fontWeight: FontWeight.bold))),
+ child: Text(AppLocalizations.of(context)!.time, style: const TextStyle(fontWeight: FontWeight.bold)),),
Expanded(
flex: _tableElementsSizes[1],
- child: Text(AppLocalizations.of(context)!.sysShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.sysColor))),
+ child: Text(AppLocalizations.of(context)!.sysShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.sysColor)),),
Expanded(
flex: _tableElementsSizes[2],
- child: Text(AppLocalizations.of(context)!.diaShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.diaColor))),
+ child: Text(AppLocalizations.of(context)!.diaShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.diaColor)),),
Expanded(
flex: _tableElementsSizes[3],
- child: Text(AppLocalizations.of(context)!.pulShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.pulColor))),
+ child: Text(AppLocalizations.of(context)!.pulShort, style: TextStyle(fontWeight: FontWeight.bold, color: settings.pulColor)),),
Expanded(
flex: _tableElementsSizes[4],
- child: Text(AppLocalizations.of(context)!.notes, style: const TextStyle(fontWeight: FontWeight.bold))),
+ child: Text(AppLocalizations.of(context)!.notes, style: const TextStyle(fontWeight: FontWeight.bold)),),
Expanded(
flex: _sideFlex,
child: const SizedBox(),
@@ -85,7 +84,7 @@ class LegacyMeasurementsList extends StatelessWidget {
if (direction == DismissDirection.startToEnd) { // edit
final model = Provider.of<BloodPressureModel>(context, listen: false);
final entry = await showAddEntryDialoge(context,
- Provider.of<Settings>(context, listen: false));
+ Provider.of<Settings>(context, listen: false),);
if (entry?.$1 != null) {
if (context.mounted) {
model.addAndExport(context, entry!.$1!);
@@ -100,14 +99,13 @@ class LegacyMeasurementsList extends StatelessWidget {
if (settings.confirmDeletion) {
await showDialog(
context: context,
- builder: (context) {
- return AlertDialog(
+ builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.confirmDelete),
content: Text(AppLocalizations.of(context)!.confirmDeleteDesc),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
- child: Text(AppLocalizations.of(context)!.btnCancel)),
+ child: Text(AppLocalizations.of(context)!.btnCancel),),
ElevatedButton(
onPressed: () {
model.delete(data[index].creationTime);
@@ -115,10 +113,9 @@ class LegacyMeasurementsList extends StatelessWidget {
dialogeDeletionConfirmed = true;
Navigator.of(context).pop();
},
- child: Text(AppLocalizations.of(context)!.btnConfirm)),
+ child: Text(AppLocalizations.of(context)!.btnConfirm),),
],
- );
- });
+ ),);
} else {
model.delete(data[index].creationTime);
dialogeDeletionConfirmed = true;
@@ -138,10 +135,10 @@ class LegacyMeasurementsList extends StatelessWidget {
data[index].systolic,
data[index].diastolic,
data[index].pulse,
- data[index].notes));
+ data[index].notes,),);
},
),
- ));
+ ),);
}
return dialogeDeletionConfirmed;
}
@@ -168,39 +165,38 @@ class LegacyMeasurementsList extends StatelessWidget {
),
Expanded(
flex: _tableElementsSizes[0],
- child: Text(formatter.format(data[index].creationTime))),
+ child: Text(formatter.format(data[index].creationTime)),),
Expanded(
flex: _tableElementsSizes[1],
- child: Text((data[index].systolic ?? '').toString())),
+ child: Text((data[index].systolic ?? '').toString()),),
Expanded(
flex: _tableElementsSizes[2],
- child: Text((data[index].diastolic ?? '').toString())),
+ child: Text((data[index].diastolic ?? '').toString()),),
Expanded(
flex: _tableElementsSizes[3],
- child: Text((data[index].pulse ?? '').toString())),
+ child: Text((data[index].pulse ?? '').toString()),),
Expanded(
flex: _tableElementsSizes[4],
- child: Text(data[index].notes)),
+ child: Text(data[index].notes),),
Expanded(
flex: _sideFlex,
child: const SizedBox(),
),
- ]),
+ ],),
),
),
const Divider(
thickness: 1,
height: 1,
- )
+ ),
],
);
- });
+ },);
} else {
return Text(AppLocalizations.of(context)!.errNoData);
}
- }),
- )
+ },),
+ ),
],
- ));
- }
+ ),);
}
lib/screens/elements/measurement_graph.dart
@@ -16,9 +16,9 @@ import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class _LineChart extends StatefulWidget {
- final double height;
const _LineChart({this.height = 200});
+ final double height;
@override
State<_LineChart> createState() => _LineChartState();
@@ -26,27 +26,25 @@ class _LineChart extends StatefulWidget {
class _LineChartState extends State<_LineChart> {
@override
- Widget build(BuildContext context) {
- return SizedBox(
+ Widget build(BuildContext context) => SizedBox(
height: widget.height,
child: Consumer<IntakeHistory>(
builder: (context, intakeHistory, child) => Consumer<Settings>(
- builder: (context, settings, child) {
- return BloodPressureBuilder(
+ builder: (context, settings, child) => BloodPressureBuilder(
rangeType: IntervallStoreManagerLocation.mainPage,
onData: (BuildContext context, UnmodifiableListView<BloodPressureRecord> records) {
- List<BloodPressureRecord> data = records.toList();
+ final List<BloodPressureRecord> data = records.toList();
data.sort((a, b) => a.creationTime.compareTo(b.creationTime));
// calculate lines for graph
List<FlSpot> pulSpots = [], diaSpots = [], sysSpots = [];
int maxValue = 0;
- int minValue = (settings.validateInputs ? 30 : 0);
+ final int minValue = (settings.validateInputs ? 30 : 0);
/// Horizontally first value
double? graphBegin;
/// Horizontally last value
double? graphEnd;
- for (var e in data) {
+ for (final e in data) {
final x = e.creationTime.millisecondsSinceEpoch.toDouble();
if (e.diastolic != null) {
diaSpots.add(FlSpot(x, e.diastolic!.toDouble()));
@@ -78,8 +76,7 @@ class _LineChartState extends State<_LineChart> {
return TweenAnimationBuilder<double>(
duration: Duration(milliseconds: settings.animationSpeed), // interacts with LineChart duration property
tween: Tween<double>(begin: 0, end: settings.graphLineThickness),
- builder: (context, animatedThickness, child) {
- return LineChart(
+ builder: (context, animatedThickness, child) => LineChart(
duration: const Duration(milliseconds: 200),
LineChartData(
minY: minValue.toDouble(),
@@ -88,30 +85,27 @@ class _LineChartState extends State<_LineChart> {
maxX: graphEnd,
clipData: const FlClipData.all(),
titlesData: _buildFlTitlesData(settings,
- DateTimeRange(start: data.first.creationTime, end: data.last.creationTime)),
+ DateTimeRange(start: data.first.creationTime, end: data.last.creationTime),),
lineTouchData: const LineTouchData(
- touchTooltipData: LineTouchTooltipData(tooltipMargin: -200, tooltipRoundedRadius: 20)
+ touchTooltipData: LineTouchTooltipData(tooltipMargin: -200, tooltipRoundedRadius: 20),
),
lineBarsData: buildBars(animatedThickness, settings, sysSpots, diaSpots, pulSpots,
maxValue, minValue, graphBegin, graphEnd, records,
intakeHistory.getIntakes(
DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(graphBegin!.toInt()),
- end: DateTime.fromMillisecondsSinceEpoch(graphEnd!.toInt())
- )
- )
- )
+ end: DateTime.fromMillisecondsSinceEpoch(graphEnd!.toInt()),
+ ),
+ ),
+ ),
),
- );
- },
+ ),
);
},
- );
- },
+ ),
),
- )
+ ),
);
- }
List<LineChartBarData> buildBars(
double animatedThickness,
@@ -128,7 +122,7 @@ class _LineChartState extends State<_LineChart> {
Iterable<BloodPressureRecord> allRecords,
Iterable<MedicineIntake> allIntakes,
) {
- var bars = [
+ final bars = [
_buildBarData(animatedThickness, sysSpots, settings.sysColor, true, settings.sysWarn.toDouble()),
_buildBarData(animatedThickness, diaSpots, settings.diaColor, true, settings.diaWarn.toDouble()),
_buildBarData(animatedThickness, pulSpots, settings.pulColor, false),
@@ -148,19 +142,19 @@ class _LineChartState extends State<_LineChart> {
bars.add(LineChartBarData(
spots: [
FlSpot(intake.timestamp.millisecondsSinceEpoch.toDouble(), minValue.toDouble()),
- FlSpot(intake.timestamp.millisecondsSinceEpoch.toDouble(), maxValue + 5)
+ FlSpot(intake.timestamp.millisecondsSinceEpoch.toDouble(), maxValue + 5),
],
barWidth: settings.needlePinBarWidth,
dotData: const FlDotData(show: false),
dashArray: [8,7],
color: intake.medicine.color,
- ));
+ ),);
}
return bars;
}
FlTitlesData _buildFlTitlesData(Settings settings, DateTimeRange graphRange) {
- const noTitels = AxisTitles(sideTitles: SideTitles(reservedSize: 40, showTitles: false));
+ const noTitels = AxisTitles(sideTitles: SideTitles(reservedSize: 40));
return FlTitlesData(
topTitles: noTitels,
rightTitles: noTitels,
@@ -187,9 +181,9 @@ class _LineChartState extends State<_LineChart> {
formatter = DateFormat.y();
}
return Text(
- formatter.format(DateTime.fromMillisecondsSinceEpoch(pos.toInt()))
+ formatter.format(DateTime.fromMillisecondsSinceEpoch(pos.toInt())),
);
- }
+ },
),
),
);
@@ -201,18 +195,17 @@ class _LineChartState extends State<_LineChart> {
pins.add(LineChartBarData(
spots: [
FlSpot(r.creationTime.millisecondsSinceEpoch.toDouble(), min.toDouble()),
- FlSpot(r.creationTime.millisecondsSinceEpoch.toDouble(), max + 5)
+ FlSpot(r.creationTime.millisecondsSinceEpoch.toDouble(), max + 5),
],
barWidth: settings.needlePinBarWidth,
dotData: const FlDotData(show: false),
color: r.needlePin!.color.withAlpha(100),
- ));
+ ),);
}
return pins;
}
- LineChartBarData _buildBarData(double lineThickness, List<FlSpot> spots, Color color, bool hasAreaData, [double? areaDataCutOff]) {
- return LineChartBarData(
+ LineChartBarData _buildBarData(double lineThickness, List<FlSpot> spots, Color color, bool hasAreaData, [double? areaDataCutOff]) => LineChartBarData(
spots: spots,
color: color,
barWidth: lineThickness,
@@ -223,9 +216,8 @@ class _LineChartState extends State<_LineChart> {
show: hasAreaData,
color: Colors.red.shade400.withAlpha(100),
cutOffY: areaDataCutOff ?? 0,
- applyCutOffY: true)
+ applyCutOffY: true,),
);
- }
// Real world use is limited
LineChartBarData _buildRegressionLine(List<FlSpot> data) {
@@ -242,56 +234,49 @@ class _LineChartState extends State<_LineChart> {
color: Colors.grey,
spots: [
FlSpot(start, y(start)),
- FlSpot(end, y(end))
+ FlSpot(end, y(end)),
],
- barWidth: 2,
dotData: const FlDotData(
show: false,
),
);
}
- LineChartBarData _buildHorizontalLine(HorizontalGraphLine line, double start, double end) {
- return LineChartBarData(
+ LineChartBarData _buildHorizontalLine(HorizontalGraphLine line, double start, double end) => LineChartBarData(
color: line.color,
spots: [
FlSpot(start, line.height.toDouble()),
- FlSpot(end, line.height.toDouble())
+ FlSpot(end, line.height.toDouble()),
],
barWidth: 1,
dotData: const FlDotData(
show: false,
),
- dashArray: [10,5,]
+ dashArray: [10,5,],
);
- }
}
class MeasurementGraph extends StatelessWidget {
- final double height;
const MeasurementGraph({super.key, this.height = 290});
+ final double height;
@override
- Widget build(BuildContext context) {
- return SizedBox(
+ Widget build(BuildContext context) => SizedBox(
height: height,
child: Padding(
padding: const EdgeInsets.only(right: 16, left: 6, top: 22),
child: Column(
children: [
_LineChart(height: height - 100),
- const IntervalPicker(type: IntervallStoreManagerLocation.mainPage,)
+ const IntervalPicker(type: IntervallStoreManagerLocation.mainPage,),
],
),
),
);
- }
}
extension Sum<T> on List<T> {
- double sum(num Function(T value) f) {
- return fold<double>(0, (prev, e) => prev + f(e).toDouble());
- }
+ double sum(num Function(T value) f) => fold<double>(0, (prev, e) => prev + f(e).toDouble());
}
lib/screens/subsettings/export_import/active_field_customization.dart
@@ -36,7 +36,7 @@ class ActiveExportFieldCustomization extends StatelessWidget {
(e) => DropdownMenuItem(
value: e,
child: Text(e.localize(localizations)),
- )
+ ),
).toList(),
onChanged: (selectedPreset) {
if (selectedPreset != null) {
@@ -66,11 +66,11 @@ class ActiveExportFieldCustomization extends StatelessWidget {
Widget _buildActiveColumnsEditor(BuildContext context,
AppLocalizations localizations,
- ActiveExportColumnConfiguration fieldsConfig) =>
+ ActiveExportColumnConfiguration fieldsConfig,) =>
Container(
margin: const EdgeInsets.symmetric(
horizontal: 16,
- vertical: 5
+ vertical: 5,
),
height: 400,
decoration: BoxDecoration(
@@ -98,9 +98,9 @@ class ActiveExportFieldCustomization extends StatelessWidget {
ListTile(
title: Text(column.userTitle(localizations)),
onTap: () => Navigator.of(context).pop(column),
- )
+ ),
).toList(),
- )
+ ),
);
if (column != null) fieldsConfig.addUserColumn(column);
},
@@ -117,7 +117,7 @@ class ActiveExportFieldCustomization extends StatelessWidget {
onPressed: () {
fieldsConfig.removeUserColumn(activeColumns[idx].internalIdentifier);
},
- icon: const Icon(Icons.remove_circle_outline)
+ icon: const Icon(Icons.remove_circle_outline),
),
const Icon(Icons.drag_handle),
],
@@ -125,9 +125,9 @@ class ActiveExportFieldCustomization extends StatelessWidget {
);
},
itemCount: activeColumns.length + 1,
- onReorder: fieldsConfig.reorderUserColumns
+ onReorder: fieldsConfig.reorderUserColumns,
);
- }
+ },
),
);
}
\ No newline at end of file
lib/screens/subsettings/export_import/export_column_management_screen.dart
@@ -28,7 +28,7 @@ class ExportColumnsManagementScreen extends StatelessWidget {
ListTile(
title: Text(column.userTitle(localizations)),
subtitle: column.formatPattern == null ? null : Text(column.formatPattern!),
- )
+ ),
],
),
ExpansionTile(
@@ -61,19 +61,19 @@ class ExportColumnsManagementScreen extends StatelessWidget {
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
- child: Text(AppLocalizations.of(context)!.btnCancel)),
+ child: Text(AppLocalizations.of(context)!.btnCancel),),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
- child: Text(AppLocalizations.of(context)!.btnConfirm)),
+ child: Text(AppLocalizations.of(context)!.btnConfirm),),
],
- )
+ ),
) ?? false;
if (confirmed) {
columnsManager.deleteUserColumn(column.internalIdentifier);
}
},
- icon: const Icon(Icons.delete)
- )
+ icon: const Icon(Icons.delete),
+ ),
],
),
),
@@ -95,11 +95,11 @@ class ExportColumnsManagementScreen extends StatelessWidget {
columnsManager.addOrUpdate(editedColumn);
}
},
- )
+ ),
],
- )
+ ),
],
- )
+ ),
),
);
}
lib/screens/subsettings/export_import/export_field_format_documentation_screen.dart
@@ -13,8 +13,7 @@ class InformationScreen extends StatelessWidget {
final String text;
@override
- Widget build(BuildContext context) {
- return Scaffold(
+ Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
forceMaterialTransparency: true,
),
@@ -23,11 +22,10 @@ class InformationScreen extends StatelessWidget {
child: Markdown(
selectable: true,
onTapLink: getLinkTapHandler(context),
- data: text
+ data: text,
),
- )
+ ),
);
- }
}
typedef LinkTapHandler = FutureOr<void> Function(String, String?, String)?;
lib/screens/subsettings/export_import/export_import_screen.dart
@@ -24,8 +24,7 @@ class ExportImportScreen extends StatelessWidget {
title: Text(localizations.exportImport),
backgroundColor: Theme.of(context).primaryColor,
),
- body: Consumer<ExportSettings>(builder: (context, settings, child) {
- return SingleChildScrollView(
+ body: Consumer<ExportSettings>(builder: (context, settings, child) => SingleChildScrollView(
child: Column(
children: [
Consumer<CsvExportSettings>(builder: (context, csvExportSettings, child) =>
@@ -33,7 +32,7 @@ class ExportImportScreen extends StatelessWidget {
ExportWarnBanner(
exportSettings: settings,
csvExportSettings: csvExportSettings,
- availableColumns: availableColumns
+ availableColumns: availableColumns,
),
),
),
@@ -55,7 +54,7 @@ class ExportImportScreen extends StatelessWidget {
} else {
settings.defaultExportDir = '';
}
- }
+ },
),
SwitchListTile(
title: Text(localizations.exportAfterEveryInput),
@@ -71,11 +70,11 @@ class ExportImportScreen extends StatelessWidget {
value: settings.exportFormat,
items: [
DropdownMenuItem(
- value: ExportFormat.csv, child: Text(localizations.csv)),
+ value: ExportFormat.csv, child: Text(localizations.csv),),
DropdownMenuItem(
- value: ExportFormat.pdf, child: Text(localizations.pdf)),
+ value: ExportFormat.pdf, child: Text(localizations.pdf),),
DropdownMenuItem(
- value: ExportFormat.db, child: Text(localizations.db)),
+ value: ExportFormat.db, child: Text(localizations.db),),
],
onChanged: (ExportFormat? value) {
if (value != null) {
@@ -107,10 +106,10 @@ class ExportImportScreen extends StatelessWidget {
value: csvExportSettings.exportHeadline,
onChanged: (value) {
csvExportSettings.exportHeadline = value;
- }
+ },
),
],
- )
+ ),
),
if (settings.exportFormat == ExportFormat.pdf)
Consumer<PdfExportSettings>(builder: (context, pdfExportSettings, child) =>
@@ -121,19 +120,19 @@ class ExportImportScreen extends StatelessWidget {
value: pdfExportSettings.exportTitle,
onChanged: (value) {
pdfExportSettings.exportTitle = value;
- }),
+ },),
SwitchListTile(
title: Text(localizations.exportPdfExportStatistics),
value: pdfExportSettings.exportStatistics,
onChanged: (value) {
pdfExportSettings.exportStatistics = value;
- }),
+ },),
SwitchListTile(
title: Text(localizations.exportPdfExportData),
value: pdfExportSettings.exportData,
onChanged: (value) {
pdfExportSettings.exportData = value;
- }),
+ },),
if (pdfExportSettings.exportData)
Column(
children: [
@@ -167,16 +166,15 @@ class ExportImportScreen extends StatelessWidget {
),
],
),
- ]
- )
+ ],
+ ),
),
ActiveExportFieldCustomization(
format: settings.exportFormat,
),
],
),
- );
- }),
+ ),),
bottomNavigationBar: const ExportButtonBar(),
);
}
lib/screens/subsettings/delete_data_screen.dart
@@ -46,9 +46,9 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
CustomBanner(
content: Text(localizations.warnNeedsRestartForUsingApp),
action: TextButton(
- onPressed: () => Restart.restartApp(),
+ onPressed: Restart.restartApp,
child: Text(localizations.restartNow),
- )
+ ),
),
Expanded(
child: Container(
@@ -59,7 +59,6 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
children: [
Text(localizations.data, style: Theme.of(context).textTheme.headlineMedium),
Expanded(
- flex: 1,
child: ListView(
children: [
ListTile(
@@ -81,9 +80,7 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
return _bytesToString(sizeBytes);
}),
- onData: (context, data) {
- return Text(data.toString());
- },
+ onData: (context, data) => Text(data),
),
trailing: const Icon(Icons.delete_forever),
onTap: () async {
@@ -118,9 +115,7 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
} on PathNotFoundException {}
return _bytesToString(sizeBytes);
}),
- onData: (context, data) {
- return Text(data.toString());
- },
+ onData: (context, data) => Text(data),
),
trailing: const Icon(Icons.delete_forever),
onTap: () async {
@@ -136,7 +131,7 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
});
}
},
- )
+ ),
],
),
),
@@ -181,14 +176,13 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
/// Converts file size in bytes to human readable string
String _bytesToString(int sizeBytes) {
- if (sizeBytes <= 0) return "0 B";
- const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
- var i = (log(sizeBytes) / log(1024)).floor();
+ if (sizeBytes <= 0) return '0 B';
+ const suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ final i = (log(sizeBytes) / log(1024)).floor();
return '${(sizeBytes / pow(1024, i)).toStringAsFixed(1)} ${suffixes[i]}';
}
- Future<bool> showDeleteDialoge(BuildContext context, AppLocalizations localizations) async {
- return await showDialog<bool>(context: context, builder: (context) =>
+ Future<bool> showDeleteDialoge(BuildContext context, AppLocalizations localizations) async => await showDialog<bool>(context: context, builder: (context) =>
AlertDialog(
title: Text(localizations.confirmDelete),
content: Text(localizations.warnDeletionUnrecoverable),
@@ -196,23 +190,22 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
- child: Text(AppLocalizations.of(context)!.btnCancel)),
+ child: Text(AppLocalizations.of(context)!.btnCancel),),
Theme(
data: ThemeData.from(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.red, brightness: Theme.of(context).brightness),
- useMaterial3: true
+ useMaterial3: true,
),
child: ElevatedButton.icon(
onPressed: () => Navigator.of(context).pop(true),
icon: const Icon(Icons.delete_forever),
- label: Text(AppLocalizations.of(context)!.btnConfirm)
+ label: Text(AppLocalizations.of(context)!.btnConfirm),
),
- )
+ ),
],
- )
+ ),
) ?? false;
- }
void tryDeleteFile(String path, ScaffoldMessengerState messanger, AppLocalizations localizations) {
try {
@@ -220,12 +213,12 @@ class _DeleteDataScreenState extends State<DeleteDataScreen> {
messanger.showSnackBar(SnackBar(
duration: const Duration(seconds: 2),
content: Text(localizations.fileDeleted),
- ));
+ ),);
} on PathNotFoundException {
messanger.showSnackBar(SnackBar(
duration: const Duration(seconds: 2),
content: Text(localizations.fileAlreadyDeleted),
- ));
+ ),);
}
}
}
\ No newline at end of file
lib/screens/subsettings/graph_markings_screen.dart
@@ -28,7 +28,7 @@ class GraphMarkingsScreen extends StatelessWidget {
padding: const EdgeInsets.all(10),
child: DefaultTextStyle.merge(
child: Text(localizations.horizontalLines),
- style: Theme.of(context).textTheme.headlineLarge
+ style: Theme.of(context).textTheme.headlineLarge,
),
);
}
@@ -65,9 +65,9 @@ class GraphMarkingsScreen extends StatelessWidget {
},
),
);
- }
+ },
);
- }),
+ },),
),
);
}
lib/screens/subsettings/medicine_manager_screen.dart
@@ -42,7 +42,7 @@ class MedicineManagerScreen extends StatelessWidget {
),
title: Text(medications[i].designation),
subtitle: Text('${localizations.defaultDosis}: '
- '${medications[i].defaultDosis?.toString()}'),
+ '${medications[i].defaultDosis}'),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
@@ -50,9 +50,9 @@ class MedicineManagerScreen extends StatelessWidget {
},
),
);
- }
+ },
);
- }),
+ },),
),
);
}
lib/screens/subsettings/time_formats_reference_screen.dart
@@ -3,7 +3,8 @@ import 'package:flutter/material.dart';
class TimeFormattingReferenceScreen extends StatelessWidget {
const TimeFormattingReferenceScreen({super.key});
// https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
- static const _formats = '''DAY d
+ static const _formats = '''
+DAY d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
@@ -42,8 +43,7 @@ class TimeFormattingReferenceScreen extends StatelessWidget {
SECOND s''';
@override
- Widget build(BuildContext context) {
- return Scaffold(
+ Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
),
@@ -53,19 +53,18 @@ class TimeFormattingReferenceScreen extends StatelessWidget {
child: Table(
columnWidths: const {
0: FlexColumnWidth(0.71),
- 1: FlexColumnWidth(0.29)
+ 1: FlexColumnWidth(0.29),
},
children: getRows(),
),
),
- ));
- }
+ ),);
List<TableRow> getRows() {
- List<TableRow> rowsOut = [];
- var lines = _formats.trim().split('\n');
+ final List<TableRow> rowsOut = [];
+ final lines = _formats.trim().split('\n');
for (int i = 1; i < lines.length; i++) {
- List<String> values = lines[i].trim().split(RegExp(r'\s{2,}'));
+ final List<String> values = lines[i].trim().split(RegExp(r'\s{2,}'));
rowsOut.add(TableRow(children: [Text(values[0]), Text(values[1])]));
}
lib/screens/subsettings/version_screen.dart
@@ -21,12 +21,12 @@ class VersionScreen extends StatelessWidget {
Clipboard.setData(ClipboardData(
text: 'Blood pressure monitor\n'
'${packageInfo.packageName}\n'
- '${packageInfo.version} - ${packageInfo.buildNumber}'
- ));
+ '${packageInfo.version} - ${packageInfo.buildNumber}',
+ ),);
},
tooltip: localizations.export,
icon: const Icon(Icons.copy),
- )
+ ),
],
backgroundColor: Theme.of(context).primaryColor,
),
@@ -35,16 +35,14 @@ class VersionScreen extends StatelessWidget {
child: Center(
child: ConsistentFutureBuilder<PackageInfo>(
future: PackageInfo.fromPlatform(),
- onData: (context, packageInfo) {
- return Column(
+ onData: (context, packageInfo) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(localizations.packageNameOf(packageInfo.packageName)),
Text(localizations.versionOf(packageInfo.version)),
Text(localizations.buildNumberOf(packageInfo.buildNumber)),
- ]
- );
- },
+ ],
+ ),
),
),
),
lib/screens/subsettings/warn_about_screen.dart
@@ -7,8 +7,7 @@ class AboutWarnValuesScreen extends StatelessWidget {
const AboutWarnValuesScreen({super.key});
@override
- Widget build(BuildContext context) {
- return Scaffold(
+ Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.warnValues),
backgroundColor: Theme.of(context).primaryColor,
@@ -32,7 +31,7 @@ class AboutWarnValuesScreen extends StatelessWidget {
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(AppLocalizations.of(context)!
- .errCantOpenURL(BloodPressureWarnValues.source))));
+ .errCantOpenURL(BloodPressureWarnValues.source),),),);
}
},
child: SizedBox(
@@ -54,5 +53,4 @@ class AboutWarnValuesScreen extends StatelessWidget {
),
),
);
- }
}
lib/screens/error_reporting_screen.dart
@@ -7,8 +7,8 @@ import 'package:sqflite/sqflite.dart';
import 'package:url_launcher/url_launcher.dart';
class ErrorReporting {
- static bool isErrorState = false;
ErrorReporting._create();
+ static bool isErrorState = false;
/// Replaces the application with an ErrorScreen
/// This method can be used to avoid running any further code in your current function, by awaiting
@@ -19,7 +19,7 @@ class ErrorReporting {
title: title,
text: text,
debugInfo: await _carefullyCollectDebugInfo(),
- ));
+ ),);
return Future.delayed(const Duration(days: 30,));
}
@@ -36,15 +36,14 @@ class ErrorReporting {
}
class ErrorScreen extends StatelessWidget {
+
+ const ErrorScreen({super.key, required this.title, required this.text, required this.debugInfo});
final String title;
final String text;
final PackageInfo debugInfo;
-
- const ErrorScreen({super.key, required this.title, required this.text, required this.debugInfo});
@override
- Widget build(BuildContext context) {
- return MaterialApp(
+ Widget build(BuildContext context) => MaterialApp(
title: 'Critical error',
home: Scaffold(
appBar: AppBar(
@@ -69,12 +68,12 @@ class ErrorScreen extends StatelessWidget {
TextButton(
onPressed: () {
Clipboard.setData(ClipboardData(
- text: 'Error:\nBuild number:${debugInfo.buildNumber}\n-----\n$title:\n---\n$text\n'
- ));
+ text: 'Error:\nBuild number:${debugInfo.buildNumber}\n-----\n$title:\n---\n$text\n',
+ ),);
scaffoldMessenger.showSnackBar(const SnackBar(
- content: Text('Copied to clipboard')));
+ content: Text('Copied to clipboard'),),);
},
- child: const Text('copy error message')
+ child: const Text('copy error message'),
),
TextButton(
onPressed: () async {
@@ -84,14 +83,14 @@ class ErrorScreen extends StatelessWidget {
await launchUrl(url, mode: LaunchMode.externalApplication);
} else {
scaffoldMessenger.showSnackBar(const SnackBar(
- content: Text('ERR: Please open this website: https://github.com/NobodyForNothing/blood-pressure-monitor-fl/issues')));
+ content: Text('ERR: Please open this website: https://github.com/NobodyForNothing/blood-pressure-monitor-fl/issues'),),);
}
} catch (e) {
scaffoldMessenger.showSnackBar(SnackBar(
- content: Text('ERR: ${e.toString()}')));
+ content: Text('ERR: $e'),),);
}
},
- child: const Text('open issue reporting website')
+ child: const Text('open issue reporting website'),
),
TextButton(
onPressed: () async {
@@ -103,10 +102,10 @@ class ErrorScreen extends StatelessWidget {
PlatformClient.shareFile(dbPath, 'application/vnd.sqlite3');
} catch(e) {
scaffoldMessenger.showSnackBar(SnackBar(
- content: Text('ERR: ${e.toString()}')));
+ content: Text('ERR: $e'),),);
}
},
- child: const Text('rescue measurements')
+ child: const Text('rescue measurements'),
),
TextButton(
onPressed: () async {
@@ -118,18 +117,17 @@ class ErrorScreen extends StatelessWidget {
PlatformClient.shareFile(dbPath, 'application/vnd.sqlite3');
} catch(e) {
scaffoldMessenger.showSnackBar(SnackBar(
- content: Text('ERR: ${e.toString()}')));
+ content: Text('ERR: $e'),),);
}
},
- child: const Text('rescue config.db')
+ child: const Text('rescue config.db'),
),
],
),
);
- }
+ },
),
),
);
- }
}
\ No newline at end of file
lib/screens/home_screen.dart
@@ -1,4 +1,5 @@
import 'package:blood_pressure_app/components/dialoges/add_measurement_dialoge.dart';
+import 'package:blood_pressure_app/components/measurement_list/measurement_list.dart';
import 'package:blood_pressure_app/model/blood_pressure/medicine/intake_history.dart';
import 'package:blood_pressure_app/model/blood_pressure/model.dart';
import 'package:blood_pressure_app/model/storage/intervall_store.dart';
@@ -14,8 +15,6 @@ import 'package:flutter/services.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
-import '../components/measurement_list/measurement_list.dart';
-
/// Is true during the first [AppHome.build] before creating the widget.
bool _appStart = true;
@@ -73,11 +72,11 @@ class AppHome extends StatelessWidget {
settings: settings,
records: records,
intakes: intakeHistory.getIntakes(intervalls.mainPage.currentRange),
- )
- )
- )
- ])
- ))
+ ),
+ ),
+ ),
+ ],),
+ ),),
),
),
);
@@ -90,15 +89,14 @@ class AppHome extends StatelessWidget {
return const SizedBox.shrink();
}
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
- return Consumer<Settings>(builder: (context, settings, child) {
- return Column(
+ return Consumer<Settings>(builder: (context, settings, child) => Column(
verticalDirection: VerticalDirection.up,
children: [
SizedBox.square(
dimension: 75,
child: FittedBox(
child: FloatingActionButton(
- heroTag: "floatingActionAdd",
+ heroTag: 'floatingActionAdd',
tooltip: localizations.addMeasurement,
autofocus: true,
onPressed: () async {
@@ -125,7 +123,7 @@ class AppHome extends StatelessWidget {
height: 10,
),
FloatingActionButton(
- heroTag: "floatingActionStatistics",
+ heroTag: 'floatingActionStatistics',
tooltip: localizations.statistics,
backgroundColor: const Color(0xFF6F6F6F),
onPressed: () {
@@ -137,7 +135,7 @@ class AppHome extends StatelessWidget {
height: 10,
),
FloatingActionButton(
- heroTag: "floatingActionSettings",
+ heroTag: 'floatingActionSettings',
tooltip: localizations.settings,
backgroundColor: const Color(0xFF6F6F6F),
child: const Icon(Icons.settings, color: Colors.black),
@@ -146,9 +144,8 @@ class AppHome extends StatelessWidget {
},
),
],
- );
- });
- })
+ ),);
+ },),
);
}
}
@@ -158,15 +155,15 @@ void _buildTransition(BuildContext context, Widget page, int duration) {
Navigator.push(context,
TimedMaterialPageRouter(
transitionDuration: Duration(milliseconds: duration),
- builder: (context) => page
- )
+ builder: (context) => page,
+ ),
);
}
class TimedMaterialPageRouter extends MaterialPageRoute {
TimedMaterialPageRouter({
required super.builder,
- required this.transitionDuration});
+ required this.transitionDuration,});
@override
final Duration transitionDuration;
lib/screens/loading_screen.dart
@@ -17,8 +17,7 @@ class LoadingScreen extends StatelessWidget {
child: TweenAnimationBuilder(
tween: Tween<double>(begin: 0, end: 1),
duration: _duration,
- builder: (BuildContext context, double value, Widget? child) {
- return Container(
+ builder: (BuildContext context, double value, Widget? child) => Container(
padding: const EdgeInsets.only(bottom: 100),
child: SizedBox.square(
dimension: dimensions.width - 20,
@@ -26,8 +25,7 @@ class LoadingScreen extends StatelessWidget {
painter: _LogoPainter(progress: value),
),
),
- );
- },
+ ),
),
),
);
@@ -43,7 +41,7 @@ class _LogoPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
- Paint paint = Paint()
+ final Paint paint = Paint()
..color = const Color.fromARGB(255, 0xb0, 0x18, 0x22)
..style = PaintingStyle.stroke
..strokeWidth = size.shortestSide / 20
@@ -84,19 +82,19 @@ class _LogoPainter extends CustomPainter {
Path _extractPathUntilLength(Path originalPath, double length,) {
final path = Path();
- var metricsIterator = originalPath.computeMetrics().iterator;
+ final metricsIterator = originalPath.computeMetrics().iterator;
var isLastSegment = false;
var currentLength = 0.0;
while (metricsIterator.moveNext() && !isLastSegment) {
- var metric = metricsIterator.current;
+ final metric = metricsIterator.current;
- var nextLength = currentLength + metric.length;
+ final nextLength = currentLength + metric.length;
isLastSegment = (nextLength > length);
assert(length - currentLength >= 0);
final pathSegment = metric.extractPath(0.0,
- min(length - currentLength, metric.length));
+ min(length - currentLength, metric.length),);
path.addPath(pathSegment, Offset.zero);
lib/screens/settings_screen.dart
@@ -35,8 +35,7 @@ class SettingsPage extends StatelessWidget {
title: Text(localizations.settings),
backgroundColor: Theme.of(context).primaryColor,
),
- body: Consumer<Settings>(builder: (context, settings, child) {
- return ListView(
+ body: Consumer<Settings>(builder: (context, settings, child) => ListView(
children: [
TitledColumn(title: Text(localizations.layout), children: [
ListTile(
@@ -48,7 +47,7 @@ class SettingsPage extends StatelessWidget {
onTap: () async {
final pickedFormat = await showTimeFormatPickerDialoge(context,
settings.dateFormatString,
- settings.bottomAppBars);
+ settings.bottomAppBars,);
if (pickedFormat != null) {
settings.dateFormatString = pickedFormat;
}
@@ -62,7 +61,7 @@ class SettingsPage extends StatelessWidget {
items: [
DropdownMenuItem(value: ThemeMode.system, child: Text(localizations.system)),
DropdownMenuItem(value: ThemeMode.dark, child: Text(localizations.dark)),
- DropdownMenuItem(value: ThemeMode.light, child: Text(localizations.light))
+ DropdownMenuItem(value: ThemeMode.light, child: Text(localizations.light)),
],
onChanged: (ThemeMode? value) {
if (value != null) settings.themeMode = value;
@@ -72,14 +71,14 @@ class SettingsPage extends StatelessWidget {
key: const Key('accentColor'),
onMainColorChanged: (color) => settings.accentColor = color,
initialColor: settings.accentColor,
- title: Text(localizations.accentColor)),
+ title: Text(localizations.accentColor),),
DropDownListTile<Locale?>(
key: const Key('language'),
leading: const Icon(Icons.language),
title: Text(localizations.language),
value: settings.language,
items: [
- DropdownMenuItem(value: null, child: Text(localizations.system)),
+ DropdownMenuItem(child: Text(localizations.system)),
for (final l in AppLocalizations.supportedLocales)
DropdownMenuItem(value: l, child: Text(getDisplayLanguage(l) ?? l.languageCode)),
],
@@ -97,7 +96,6 @@ class SettingsPage extends StatelessWidget {
value: settings.graphLineThickness,
min: 1,
max: 5,
- stepSize: 1,
),
SliderListTile(
key: const Key('needlePinBarWidth'),
@@ -110,7 +108,6 @@ class SettingsPage extends StatelessWidget {
value: settings.needlePinBarWidth,
min: 1,
max: 20,
- stepSize: 1,
),
SliderListTile(
key: const Key('animationSpeed'),
@@ -128,17 +125,17 @@ class SettingsPage extends StatelessWidget {
key: const Key('sysColor'),
onMainColorChanged: (color) => settings.sysColor = color,
initialColor: settings.sysColor,
- title: Text(localizations.sysColor)),
+ title: Text(localizations.sysColor),),
ColorSelectionListTile(
key: const Key('diaColor'),
onMainColorChanged: (color) => settings.diaColor = color,
initialColor: settings.diaColor,
- title: Text(localizations.diaColor)),
+ title: Text(localizations.diaColor),),
ColorSelectionListTile(
key: const Key('pulColor'),
onMainColorChanged: (color) => settings.pulColor = color,
initialColor: settings.pulColor,
- title: Text(localizations.pulColor)),
+ title: Text(localizations.pulColor),),
SwitchListTile(
key: const Key('useLegacyList'),
value: settings.useLegacyList,
@@ -147,17 +144,17 @@ class SettingsPage extends StatelessWidget {
},
secondary: const Icon(Icons.list_alt_outlined),
title: Text(localizations.useLegacyList),),
- ]),
+ ],),
TitledColumn(title: Text(localizations.behavior), children: [
ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder:
- (context) => const MedicineManagerScreen()));
+ (context) => const MedicineManagerScreen(),),);
},
leading: const Icon(Icons.medication),
title: Text(localizations.medications),
- trailing: const Icon(Icons.arrow_forward_ios)
+ trailing: const Icon(Icons.arrow_forward_ios),
),
SwitchListTile(
key: const Key('allowManualTimeInput'),
@@ -166,7 +163,7 @@ class SettingsPage extends StatelessWidget {
settings.allowManualTimeInput = value;
},
secondary: const Icon(Icons.details),
- title: Text(localizations.allowManualTimeInput)),
+ title: Text(localizations.allowManualTimeInput),),
SwitchListTile(
key: const Key('validateInputs'),
value: settings.validateInputs,
@@ -175,7 +172,7 @@ class SettingsPage extends StatelessWidget {
onChanged: settings.allowMissingValues ? null : (value) {
assert(!settings.allowMissingValues);
settings.validateInputs = value;
- }),
+ },),
SwitchListTile(
key: const Key('allowMissingValues'),
value: settings.allowMissingValues,
@@ -184,7 +181,7 @@ class SettingsPage extends StatelessWidget {
onChanged: (value) {
settings.allowMissingValues = value;
if (value) settings.validateInputs = false;
- }),
+ },),
SwitchListTile(
key: const Key('confirmDeletion'),
value: settings.confirmDeletion,
@@ -192,7 +189,7 @@ class SettingsPage extends StatelessWidget {
secondary: const Icon(Icons.check),
onChanged: (value) {
settings.confirmDeletion = value;
- }),
+ },),
NumberInputListTile(
key: const Key('sysWarn'),
label: localizations.sysWarn,
@@ -236,7 +233,7 @@ class SettingsPage extends StatelessWidget {
context,
MaterialPageRoute(builder: (context) => const AboutWarnValuesScreen()),
);
- }
+ },
),
ListTile(
key: const Key('GraphMarkingsScreen'),
@@ -248,7 +245,7 @@ class SettingsPage extends StatelessWidget {
context,
MaterialPageRoute(builder: (context) => const GraphMarkingsScreen()),
);
- }
+ },
),
SwitchListTile(
title: Text(localizations.drawRegressionLines),
@@ -257,7 +254,7 @@ class SettingsPage extends StatelessWidget {
value: settings.drawRegressionLines,
onChanged: (value) {
settings.drawRegressionLines = value;
- }
+ },
),
SwitchListTile(
title: Text(localizations.startWithAddMeasurementPage),
@@ -266,7 +263,7 @@ class SettingsPage extends StatelessWidget {
value: settings.startWithAddMeasurementPage,
onChanged: (value) {
settings.startWithAddMeasurementPage = value;
- }
+ },
),
SwitchListTile(
title: Text(localizations.bottomAppBars),
@@ -274,9 +271,9 @@ class SettingsPage extends StatelessWidget {
value: settings.bottomAppBars,
onChanged: (value) {
settings.bottomAppBars = value;
- }
+ },
),
- ]),
+ ],),
TitledColumn(
title: Text(localizations.data),
children: [
@@ -289,7 +286,7 @@ class SettingsPage extends StatelessWidget {
context,
MaterialPageRoute(builder: (context) => const ExportImportScreen()),
);
- }
+ },
),
ListTile(
title: Text(localizations.exportSettings),
@@ -300,7 +297,7 @@ class SettingsPage extends StatelessWidget {
dbPath = join(dbPath, 'config.db');
assert(Platform.isAndroid);
PlatformClient.shareFile(dbPath, 'application/vnd.sqlite3');
- }
+ },
),
ListTile(
title: Text(localizations.importSettings),
@@ -308,15 +305,14 @@ class SettingsPage extends StatelessWidget {
leading: const Icon(Icons.settings_backup_restore),
onTap: () async {
final messenger = ScaffoldMessenger.of(context);
- var result = await FilePicker.platform.pickFiles(
- allowMultiple: false,
- withData: false,
+ final result = await FilePicker.platform.pickFiles(
+
);
if (result == null) {
messenger.showSnackBar(SnackBar(content: Text(localizations.errNoFileOpened)));
return;
}
- var path = result.files.single.path;
+ final path = result.files.single.path;
if (path == null) {
messenger.showSnackBar(SnackBar(content: Text(localizations.errCantReadFile)));
return;
@@ -330,7 +326,7 @@ class SettingsPage extends StatelessWidget {
messenger.showSnackBar(SnackBar(content: Text(localizations.pleaseRestart)));
return;
}
- }
+ },
),
ListTile(
title: Text(localizations.delete),
@@ -341,8 +337,8 @@ class SettingsPage extends StatelessWidget {
context,
MaterialPageRoute(builder: (context) => const DeleteDataScreen()),
);
- }
- )
+ },
+ ),
],
),
TitledColumn(title: Text(localizations.aboutWarnValuesScreen), children: [
@@ -354,14 +350,14 @@ class SettingsPage extends StatelessWidget {
subtitle: ConsistentFutureBuilder<PackageInfo>(
future: PackageInfo.fromPlatform(),
cacheFuture: true,
- onData: (context, info) => Text(info.version)
+ onData: (context, info) => Text(info.version),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const VersionScreen()),
);
- }
+ },
),
ListTile(
key: const Key('sourceCode'),
@@ -370,12 +366,12 @@ class SettingsPage extends StatelessWidget {
trailing: const Icon(Icons.open_in_new),
onTap: () async {
final scaffoldMessenger = ScaffoldMessenger.of(context);
- var url = Uri.parse('https://github.com/NobodyForNothing/blood-pressure-monitor-fl');
+ final url = Uri.parse('https://github.com/NobodyForNothing/blood-pressure-monitor-fl');
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
} else {
scaffoldMessenger.showSnackBar(SnackBar(
- content: Text(localizations.errCantOpenURL(url.toString()))));
+ content: Text(localizations.errCantOpenURL(url.toString())),),);
}
},
),
@@ -388,10 +384,9 @@ class SettingsPage extends StatelessWidget {
showLicensePage(context: context);
},
),
- ])
+ ],),
],
- );
- }),
+ ),),
);
}
}
lib/screens/statistics_screen.dart
@@ -14,15 +14,13 @@ class StatisticsPage extends StatelessWidget {
const StatisticsPage({super.key});
@override
- Widget build(BuildContext context) {
- return Scaffold(
+ Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.statistics),
backgroundColor: Theme.of(context).primaryColor,
),
body: SingleChildScrollView(
- child: Consumer<Settings>(builder: (context, settings, child) {
- return BloodPressureBuilder(
+ child: Consumer<Settings>(builder: (context, settings, child) => BloodPressureBuilder(
rangeType: IntervallStoreManagerLocation.statsPage,
onData: (context, data) {
final analyzer = BloodPressureAnalyser(data.toList());
@@ -30,7 +28,7 @@ class StatisticsPage extends StatelessWidget {
children: [
Statistic(
key: const Key('measurementCount'),
- caption: Text(AppLocalizations.of(context)!.measurementCount), child: displayInt(analyzer.count)),
+ caption: Text(AppLocalizations.of(context)!.measurementCount), child: displayInt(analyzer.count),),
// special measurements
StatisticsRow(
caption1: Text(
@@ -51,7 +49,7 @@ class StatisticsPage extends StatelessWidget {
),
Statistic(
caption: Text(AppLocalizations.of(context)!.measurementsPerDay),
- child: displayInt(analyzer.measurementsPerDay)),
+ child: displayInt(analyzer.measurementsPerDay),),
StatisticsRow(
caption1: Text(
AppLocalizations.of(context)!.minOf(AppLocalizations.of(context)!.sysLong),
@@ -116,19 +114,19 @@ class StatisticsPage extends StatelessWidget {
borderColor: settings.diaColor,
fillColor: settings.diaColor.withOpacity(opacity),
entryRadius: 0,
- borderWidth: settings.graphLineThickness),
+ borderWidth: settings.graphLineThickness,),
RadarDataSet(
dataEntries: intListToRadarEntry(data[1]),
borderColor: settings.sysColor,
fillColor: settings.sysColor.withOpacity(opacity),
entryRadius: 0,
- borderWidth: settings.graphLineThickness),
+ borderWidth: settings.graphLineThickness,),
RadarDataSet(
dataEntries: intListToRadarEntry(data[2]),
borderColor: settings.pulColor,
fillColor: settings.pulColor.withOpacity(opacity),
entryRadius: 0,
- borderWidth: settings.graphLineThickness),
+ borderWidth: settings.graphLineThickness,),
],
),
),
@@ -137,21 +135,19 @@ class StatisticsPage extends StatelessWidget {
),
],
);
- }
- );
- }
- )),
+ },
+ ),
+ ),),
bottomNavigationBar: Container(
height: 70,
margin: const EdgeInsets.only(top: 15, bottom: 5),
child: const IntervalPicker(type: IntervallStoreManagerLocation.statsPage,),
- )
+ ),
);
- }
List<RadarEntry> intListToRadarEntry(List<int> data) {
- var res = <RadarEntry>[];
- for (var v in data) {
+ final res = <RadarEntry>[];
+ for (final v in data) {
res.add(RadarEntry(value: v.toDouble()));
}
return res;
@@ -159,13 +155,13 @@ class StatisticsPage extends StatelessWidget {
}
class Statistic extends StatelessWidget {
+
+ const Statistic({super.key, required this.caption, required this.child, this.smallEdges = false});
final Widget caption;
final Widget child;
/// Reduces the padding at the sites to allow packing [Statistic] widgets tighter together.
final bool smallEdges;
- const Statistic({super.key, required this.caption, required this.child, this.smallEdges = false});
-
@override
Widget build(BuildContext context) {
const double top = 20;
@@ -189,17 +185,16 @@ class Statistic extends StatelessWidget {
left: 12,
child: DefaultTextStyle(
style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color ?? Colors.white38),
- child: caption),
+ child: caption,),
),
Container(
padding: EdgeInsets.only(left: padding, right: padding, bottom: padding, top: padding + 5),
child: Align(
- alignment: Alignment.center,
child: DefaultTextStyle(
style: Theme.of(context).textTheme.displaySmall!,
child: FittedBox(
fit: BoxFit.fitHeight,
- child: child
+ child: child,
),
),
),
@@ -211,12 +206,6 @@ class Statistic extends StatelessWidget {
}
class StatisticsRow extends StatelessWidget {
- final Widget caption1;
- final Widget caption2;
- final Widget caption3;
- final Widget child1;
- final Widget child2;
- final Widget child3;
const StatisticsRow(
{super.key,
@@ -225,11 +214,16 @@ class StatisticsRow extends StatelessWidget {
required this.caption3,
required this.child1,
required this.child2,
- required this.child3});
+ required this.child3,});
+ final Widget caption1;
+ final Widget caption2;
+ final Widget caption3;
+ final Widget child1;
+ final Widget child2;
+ final Widget child3;
@override
- Widget build(BuildContext context) {
- return Row(
+ Widget build(BuildContext context) => Row(
children: [
const SizedBox(
width: 20,
@@ -266,7 +260,6 @@ class StatisticsRow extends StatelessWidget {
),
],
);
- }
}
Widget displayInt(int value) {
lib/main.dart
@@ -27,8 +27,8 @@ void main() async {
runApp(ConsistentFutureBuilder(
future: _loadApp(),
onWaiting: const LoadingScreen(),
- onData: (context, widget) => widget
- ));
+ onData: (context, widget) => widget,
+ ),);
}
/// Load the primary app data asynchronously to allow adding load animations.
@@ -98,29 +98,24 @@ Future<Widget> _loadApp() async {
ChangeNotifierProvider(create: (context) => intervalStorageManager),
ChangeNotifierProvider(create: (context) => exportColumnsManager),
ChangeNotifierProvider(create: (context) => intakeHistory),
- ], child: const AppRoot());
+ ], child: const AppRoot(),);
}
class AppRoot extends StatelessWidget {
const AppRoot({super.key});
@override
- Widget build(BuildContext context) {
- return Consumer<Settings>(builder: (context, settings, child) {
- return MaterialApp(
+ Widget build(BuildContext context) => Consumer<Settings>(builder: (context, settings, child) => MaterialApp(
title: 'Blood Pressure App',
- onGenerateTitle: (context) {
- return AppLocalizations.of(context)!.title;
- },
+ onGenerateTitle: (context) => AppLocalizations.of(context)!.title,
theme: _buildTheme(ColorScheme.fromSeed(
seedColor: settings.accentColor,
- brightness: Brightness.light,
- )),
+ ),),
darkTheme: _buildTheme(ColorScheme.fromSeed(
seedColor: settings.accentColor,
brightness: Brightness.dark,
background: Colors.black,
- )),
+ ),),
themeMode: settings.themeMode,
localizationsDelegates: const [
AppLocalizations.delegate,
@@ -131,9 +126,7 @@ class AppRoot extends StatelessWidget {
supportedLocales: AppLocalizations.supportedLocales,
locale: settings.language,
home: const AppHome(),
- );
- });
- }
+ ),);
ThemeData _buildTheme(ColorScheme colorScheme) {
final inputBorder = OutlineInputBorder(
@@ -144,7 +137,7 @@ class AppRoot extends StatelessWidget {
? colorScheme.outlineVariant
: colorScheme.outline,
),
- borderRadius: BorderRadius.circular(20)
+ borderRadius: BorderRadius.circular(20),
);
return ThemeData(
test/model/export_import/column_test.dart
@@ -19,11 +19,11 @@ void main() {
NativeColumn.notes,
NativeColumn.color,
NativeColumn.needlePin,
- ]));
+ ]),);
});
test('should have internalIdentifier prefixed with "native."', () {
for (final c in NativeColumn.allColumns) {
- expect(c.internalIdentifier, startsWith("native."));
+ expect(c.internalIdentifier, startsWith('native.'));
}
});
test('should encode into non-empty string', () {
@@ -47,27 +47,27 @@ void main() {
switch (decoded!.$1) {
case RowDataFieldType.timestamp:
expect(decoded.$2, isA<DateTime>().having(
- (p0) => p0.millisecondsSinceEpoch, 'milliseconds', r.creationTime.millisecondsSinceEpoch));
+ (p0) => p0.millisecondsSinceEpoch, 'milliseconds', r.creationTime.millisecondsSinceEpoch,),);
break;
case RowDataFieldType.sys:
expect(decoded.$2, isA<int>().having(
- (p0) => p0, 'systolic', r.systolic));
+ (p0) => p0, 'systolic', r.systolic,),);
break;
case RowDataFieldType.dia:
expect(decoded.$2, isA<int>().having(
- (p0) => p0, 'diastolic', r.diastolic));
+ (p0) => p0, 'diastolic', r.diastolic,),);
break;
case RowDataFieldType.pul:
expect(decoded.$2, isA<int>().having(
- (p0) => p0, 'pulse', r.pulse));
+ (p0) => p0, 'pulse', r.pulse,),);
break;
case RowDataFieldType.notes:
expect(decoded.$2, isA<String>().having(
- (p0) => p0, 'pulse', r.notes));
+ (p0) => p0, 'pulse', r.notes,),);
break;
case RowDataFieldType.needlePin:
expect(decoded.$2, isA<MeasurementNeedlePin>().having(
- (p0) => p0.toJson(), 'pin', r.needlePin?.toJson()));
+ (p0) => p0.toJson(), 'pin', r.needlePin?.toJson(),),);
break;
}
}
@@ -86,11 +86,11 @@ void main() {
BuildInColumn.mhTags,
BuildInColumn.mhWeight,
BuildInColumn.mhOxygen,
- ]));
+ ]),);
});
test('should have internalIdentifier prefixed with "buildin."', () {
for (final c in BuildInColumn.allColumns) {
- expect(c.internalIdentifier, startsWith("buildin."));
+ expect(c.internalIdentifier, startsWith('buildin.'));
}
});
test('should encode without problems', () {
@@ -110,31 +110,31 @@ void main() {
expect(decoded?.$2, isA<DateTime>().having(
(p0) => p0.difference(r.creationTime).inDays,
'inaccuracy',
- lessThan(1)));
+ lessThan(1),),);
} else {
expect(decoded?.$2, isA<DateTime>().having(
- (p0) => p0.millisecondsSinceEpoch, 'milliseconds', r.creationTime.millisecondsSinceEpoch));
+ (p0) => p0.millisecondsSinceEpoch, 'milliseconds', r.creationTime.millisecondsSinceEpoch,),);
}
break;
case RowDataFieldType.sys:
expect(decoded?.$2, isA<int>().having(
- (p0) => p0, 'systolic', r.systolic));
+ (p0) => p0, 'systolic', r.systolic,),);
break;
case RowDataFieldType.dia:
expect(decoded?.$2, isA<int>().having(
- (p0) => p0, 'diastolic', r.diastolic));
+ (p0) => p0, 'diastolic', r.diastolic,),);
break;
case RowDataFieldType.pul:
expect(decoded?.$2, isA<int>().having(
- (p0) => p0, 'pulse', r.pulse));
+ (p0) => p0, 'pulse', r.pulse,),);
break;
case RowDataFieldType.notes:
expect(decoded?.$2, isA<String>().having(
- (p0) => p0, 'pulse', r.notes));
+ (p0) => p0, 'pulse', r.notes,),);
break;
case RowDataFieldType.needlePin:
expect(decoded?.$2, isA<MeasurementNeedlePin>().having(
- (p0) => p0.toJson(), 'pin', r.needlePin?.toJson()));
+ (p0) => p0.toJson(), 'pin', r.needlePin?.toJson(),),);
break;
case null:
break;
@@ -181,5 +181,5 @@ BloodPressureRecord _filledRecord() => mockRecord(
dia: 456,
pul: 789,
note: 'test',
- pin: Colors.pink
+ pin: Colors.pink,
);
\ No newline at end of file
test/model/export_import/csv_converter_test.dart
@@ -28,7 +28,7 @@ void main() {
test('should not create first line when setting is off', () {
final converter = CsvConverter(
CsvExportSettings(exportHeadline: false),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final csv = converter.create([]);
final columns = CsvExportSettings().exportFieldsConfiguration.getActiveColumns(ExportColumnsManager());
@@ -49,14 +49,14 @@ void main() {
p0.pulse == p1.pulse &&
p0.notes == p1.notes &&
p0.needlePin?.color == p1.needlePin?.color,
- 'equal to'));
+ 'equal to',),);
});
test('should allow partial imports', () {
final text = File('test/model/export_import/exported_formats/incomplete_export.csv').readAsStringSync();
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -68,24 +68,24 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', null)
.having((p0) => p0.pulse, 'pulse', null)
.having((p0) => p0.notes, 'notes', 'note')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703239908244)
.having((p0) => p0.systolic, 'systolic', null)
.having((p0) => p0.diastolic, 'diastolic', 45)
.having((p0) => p0.pulse, 'pulse', null)
.having((p0) => p0.notes, 'notes', 'test')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703239905395)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', null)
.having((p0) => p0.pulse, 'pulse', null)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
});
@@ -94,7 +94,7 @@ void main() {
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -106,22 +106,22 @@ void main() {
.having((p0) => p0.systolic, 'systolic', 312)
.having((p0) => p0.diastolic, 'diastolic', 315)
.having((p0) => p0.pulse, 'pulse', 46)
- .having((p0) => p0.notes.trim(), 'notes', 'testfkajkfb')
- ));
+ .having((p0) => p0.notes.trim(), 'notes', 'testfkajkfb'),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703175600000)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', 41)
.having((p0) => p0.pulse, 'pulse', 43)
- .having((p0) => p0.notes.trim(), 'notes', '1214s3')
- ));
+ .having((p0) => p0.notes.trim(), 'notes', '1214s3'),
+ ),);
});
test('should import v1.1.0 measurements', () {
final text = File('test/model/export_import/exported_formats/v1.1.0').readAsStringSync();
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -133,22 +133,22 @@ void main() {
.having((p0) => p0.systolic, 'systolic', 312)
.having((p0) => p0.diastolic, 'diastolic', 315)
.having((p0) => p0.pulse, 'pulse', 46)
- .having((p0) => p0.notes.trim(), 'notes', 'testfkajkfb')
- ));
+ .having((p0) => p0.notes.trim(), 'notes', 'testfkajkfb'),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703175600000)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', 41)
.having((p0) => p0.pulse, 'pulse', 43)
- .having((p0) => p0.notes.trim(), 'notes', '1214s3')
- ));
+ .having((p0) => p0.notes.trim(), 'notes', '1214s3'),
+ ),);
});
test('should import v1.4.0 measurements', () {
final text = File('test/model/export_import/exported_formats/v1.4.0.CSV').readAsStringSync();
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -160,29 +160,29 @@ void main() {
.having((p0) => p0.systolic, 'systolic', 312)
.having((p0) => p0.diastolic, 'diastolic', 315)
.having((p0) => p0.pulse, 'pulse', 46)
- .having((p0) => p0.notes, 'notes', 'testfkajkfb')
- ));
+ .having((p0) => p0.notes, 'notes', 'testfkajkfb'),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703175600000)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', 41)
.having((p0) => p0.pulse, 'pulse', 43)
- .having((p0) => p0.notes, 'notes', '1214s3')
- ));
+ .having((p0) => p0.notes, 'notes', '1214s3'),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 10893142303200)
.having((p0) => p0.systolic, 'systolic', 106)
.having((p0) => p0.diastolic, 'diastolic', 77)
.having((p0) => p0.pulse, 'pulse', 53)
- .having((p0) => p0.notes, 'notes', '')
- ));
+ .having((p0) => p0.notes, 'notes', ''),
+ ),);
});
test('should import v1.5.1 measurements', () {
final text = File('test/model/export_import/exported_formats/v1.5.1.csv').readAsStringSync();
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -195,31 +195,31 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', 315)
.having((p0) => p0.pulse, 'pulse', 46)
.having((p0) => p0.notes, 'notes', 'testfkajkfb')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703175600000)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', 41)
.having((p0) => p0.pulse, 'pulse', 43)
.having((p0) => p0.notes, 'notes', '1214s3')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1077625200000)
.having((p0) => p0.systolic, 'systolic', 100)
.having((p0) => p0.diastolic, 'diastolic', 82)
.having((p0) => p0.pulse, 'pulse', 63)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
});
test('should import v1.5.7 measurements', () {
final text = File('test/model/export_import/exported_formats/v1.5.7.csv').readAsStringSync();
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -232,24 +232,24 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', 315)
.having((p0) => p0.pulse, 'pulse', 46)
.having((p0) => p0.notes, 'notes', 'testfkajkfb')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1703175600000)
.having((p0) => p0.systolic, 'systolic', 123)
.having((p0) => p0.diastolic, 'diastolic', 41)
.having((p0) => p0.pulse, 'pulse', 43)
.having((p0) => p0.notes, 'notes', '1214s3')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1077625200000)
.having((p0) => p0.systolic, 'systolic', 100)
.having((p0) => p0.diastolic, 'diastolic', 82)
.having((p0) => p0.pulse, 'pulse', 63)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
// TODO: test color
});
test('should import v1.5.8 measurements', () {
@@ -257,7 +257,7 @@ void main() {
final converter = CsvConverter(
CsvExportSettings(),
- ExportColumnsManager()
+ ExportColumnsManager(),
);
final parsed = converter.parse(text);
final records = parsed.getOr(failParse);
@@ -270,32 +270,32 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', 43)
.having((p0) => p0.pulse, 'pulse', 53)
.having((p0) => p0.notes, 'notes', 'sdfsdfds')
- .having((p0) => p0.needlePin?.color, 'pin', const Color(0xff69f0ae))
- ));
+ .having((p0) => p0.needlePin?.color, 'pin', const Color(0xff69f0ae)),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1702883511000)
.having((p0) => p0.systolic, 'systolic', 114)
.having((p0) => p0.diastolic, 'diastolic', 71)
.having((p0) => p0.pulse, 'pulse', 66)
.having((p0) => p0.notes, 'notes', 'fsaf &_*¢|^✓[=%®©')
- .having((p0) => p0.needlePin?.color.value, 'pin', Colors.lightGreen.value)
- ));
+ .having((p0) => p0.needlePin?.color.value, 'pin', Colors.lightGreen.value),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1701034952000)
.having((p0) => p0.systolic, 'systolic', 125)
.having((p0) => p0.diastolic, 'diastolic', 77)
.having((p0) => p0.pulse, 'pulse', 60)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
expect(records, anyElement(isA<BloodPressureRecord>()
.having((p0) => p0.creationTime.millisecondsSinceEpoch, 'timestamp', 1077625200000)
.having((p0) => p0.systolic, 'systolic', 100)
.having((p0) => p0.diastolic, 'diastolic', 82)
.having((p0) => p0.pulse, 'pulse', 63)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin, 'pin', null)
- ));
+ .having((p0) => p0.needlePin, 'pin', null),
+ ),);
// TODO: test time columns
});
});
@@ -304,7 +304,7 @@ void main() {
List<BloodPressureRecord> createRecords([int count = 20]) => [
for (int i = 0; i<count; i++)
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(123456 + i),
- i, 100+i, 200+1, 'note $i', needlePin: MeasurementNeedlePin(Color(123+i))),
+ i, 100+i, 200+1, 'note $i', needlePin: MeasurementNeedlePin(Color(123+i)),),
];
List<BloodPressureRecord>? failParse(RecordParsingError error) {
test/model/export_import/export_configuration_test.dart
@@ -10,7 +10,7 @@ void main() {
ActiveExportColumnConfiguration();
ActiveExportColumnConfiguration(activePreset: ExportImportPreset.myHeart);
ActiveExportColumnConfiguration(activePreset: ExportImportPreset.none, userSelectedColumnIds: ['a','b','c']);
- ActiveExportColumnConfiguration(activePreset: null, userSelectedColumnIds: ['a','b','c']);
+ ActiveExportColumnConfiguration(userSelectedColumnIds: ['a','b','c']);
});
test('should return correct columns depending on mode', () {
test/model/export_import/pdf_converter_test.dart
@@ -60,5 +60,5 @@ void main() {
List<BloodPressureRecord> createRecords([int count = 20]) => [
for (int i = 0; i<count; i++)
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(123456 + i),
- i, 100+i, 200+1, 'note $i', needlePin: MeasurementNeedlePin(Color(123+i))),
+ i, 100+i, 200+1, 'note $i', needlePin: MeasurementNeedlePin(Color(123+i)),),
];
test/model/export_import/record_formatter_test.dart
@@ -20,7 +20,7 @@ void main() {
});
test('should create correct strings', () {
final testRecord = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), 123, 45, 67, 'Test',
- needlePin: const MeasurementNeedlePin(Colors.red));
+ needlePin: const MeasurementNeedlePin(Colors.red),);
expect(ScriptedFormatter(r'constant text',).encode(testRecord), 'constant text');
expect(ScriptedFormatter(r'$SYS',).encode(testRecord), testRecord.systolic.toString());
@@ -30,18 +30,18 @@ void main() {
expect(ScriptedFormatter(r'$NOTE',).encode(testRecord), testRecord.notes);
expect(ScriptedFormatter(r'$TIMESTAMP',).encode(testRecord), testRecord.creationTime.millisecondsSinceEpoch.toString());
expect(ScriptedFormatter(r'$SYS$DIA$PUL',).encode(testRecord), (testRecord.systolic.toString()
- + testRecord.diastolic.toString() + testRecord.pulse.toString()));
+ + testRecord.diastolic.toString() + testRecord.pulse.toString()),);
expect(ScriptedFormatter(r'$SYS$SYS',).encode(testRecord), (testRecord.systolic.toString()
- + testRecord.systolic.toString()));
+ + testRecord.systolic.toString()),);
expect(ScriptedFormatter(r'{{$SYS-$DIA}}',).encode(testRecord),
- (testRecord.systolic! - testRecord.diastolic!).toDouble().toString());
+ (testRecord.systolic! - testRecord.diastolic!).toDouble().toString(),);
expect(ScriptedFormatter(r'{{$SYS*$DIA-$PUL}}',).encode(testRecord),
- (testRecord.systolic! * testRecord.diastolic! - testRecord.pulse!).toDouble().toString());
+ (testRecord.systolic! * testRecord.diastolic! - testRecord.pulse!).toDouble().toString(),);
expect(ScriptedFormatter(r'$SYS-$DIA',).encode(testRecord), ('${testRecord.systolic}-${testRecord.diastolic}'));
final formatter = DateFormat.yMMMMEEEEd();
expect(ScriptedFormatter('\$FORMAT{\$TIMESTAMP,${formatter.pattern}}',).encode(testRecord),
- formatter.format(testRecord.creationTime));
+ formatter.format(testRecord.creationTime),);
});
test('should report correct reversibility', () {
expect(ScriptedFormatter(r'$SYS',).restoreAbleType, RowDataFieldType.sys);
@@ -68,10 +68,10 @@ void main() {
expect(ScriptedFormatter(r'$NOTE',).decode('test note'), (RowDataFieldType.notes, 'test note'));
final encodedPurple = ScriptedFormatter(r'$COLOR',)
.encode(BloodPressureRecord(DateTime.now(), null, null, null, '',
- needlePin: const MeasurementNeedlePin(Colors.purple)));
+ needlePin: const MeasurementNeedlePin(Colors.purple),),);
expect(ScriptedFormatter(r'$COLOR',).decode(encodedPurple)?.$1, RowDataFieldType.needlePin);
expect(ScriptedFormatter(r'$COLOR',).decode(encodedPurple)?.$2, isA<MeasurementNeedlePin>()
- .having((p0) => p0.color.value, 'color', Colors.purple.value));
+ .having((p0) => p0.color.value, 'color', Colors.purple.value),);
expect(ScriptedFormatter(r'test$SYS',).decode('test567'), (RowDataFieldType.sys, 567));
expect(ScriptedFormatter(r'test$SYS123',).decode('test567123'), (RowDataFieldType.sys, 567));
expect(ScriptedFormatter(r'test$DIA123',).decode('test567123'), (RowDataFieldType.dia, 567));
@@ -118,7 +118,7 @@ void main() {
final r = mockRecord();
expect(formatter.encode(r), isNotNull);
expect(formatter.decode(formatter.encode(r))?.$2, isA<DateTime>()
- .having((p0) => p0.millisecondsSinceEpoch, 'time(up to one second difference)', closeTo(r.creationTime.millisecondsSinceEpoch, 1000)));
+ .having((p0) => p0.millisecondsSinceEpoch, 'time(up to one second difference)', closeTo(r.creationTime.millisecondsSinceEpoch, 1000)),);
});
});
}
@@ -136,4 +136,4 @@ BloodPressureRecord mockRecord({
dia,
pul,
note ?? '',
- needlePin: pin == null ? null : MeasurementNeedlePin(pin));
\ No newline at end of file
+ needlePin: pin == null ? null : MeasurementNeedlePin(pin),);
\ No newline at end of file
test/model/medicine/intake_history_test.dart
@@ -24,8 +24,8 @@ void main() {
]);
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(4),
- end: DateTime.fromMillisecondsSinceEpoch(15)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(15),
+ ),);
expect(found.length, 8);
expect(found.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([4,5,6,9,9,12,15,15]));
});
@@ -36,8 +36,8 @@ void main() {
]);
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(4)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(4),
+ ),);
expect(found.length, 2);
expect(found.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([2,3]));
});
@@ -45,8 +45,8 @@ void main() {
final history = IntakeHistory([]);
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(1000)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(1000),
+ ),);
expect(found.length, 0);
});
test('should return nothing when intakes are out of range', () {
@@ -56,13 +56,13 @@ void main() {
]);
final found1 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(4),
- end: DateTime.fromMillisecondsSinceEpoch(10)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(10),
+ ),);
expect(found1.length, 0);
final found2 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(1)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(1),
+ ),);
expect(found2.length, 0);
});
test('should add to the correct position', () {
@@ -74,32 +74,32 @@ void main() {
history.addIntake(mockIntake(timeMs: 3));
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(10)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(10),
+ ),);
expect(found.length, 3);
expect(found.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([2,3,7]));
history.addIntake(mockIntake(timeMs: 3));
final found2 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(10)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(10),
+ ),);
expect(found2.length, 4);
expect(found2.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([2,3,3,7]));
history.addIntake(mockIntake(timeMs: 1));
final found3 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(10)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(10),
+ ),);
expect(found3.length, 5);
expect(found3.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([1,2,3,3,7]));
history.addIntake(mockIntake(timeMs: 10));
final found4 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(10)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(10),
+ ),);
expect(found4.length, 6);
expect(found4.map((e) => e.timestamp.millisecondsSinceEpoch), containsAllInOrder([1,2,3,3,7,10]));
});
@@ -117,37 +117,37 @@ void main() {
history.deleteIntake(mockIntake(timeMs: 5));
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(20)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(20),
+ ),);
expect(found.length, 7);
expect(found.map((e) => e.timestamp.millisecondsSinceEpoch),
- containsAllInOrder([2,2,4,6,9,9,12]));
+ containsAllInOrder([2,2,4,6,9,9,12]),);
history.deleteIntake(mockIntake(timeMs: 9));
final found3 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(20)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(20),
+ ),);
expect(found3.length, 6);
expect(found3.map((e) => e.timestamp.millisecondsSinceEpoch),
- containsAllInOrder([2,2,4,6,9,12]));
+ containsAllInOrder([2,2,4,6,9,12]),);
history.deleteIntake(mockIntake(timeMs: 2));
final found4 = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(20)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(20),
+ ),);
expect(found4.length, 4);
expect(found4.map((e) => e.timestamp.millisecondsSinceEpoch),
- containsAllInOrder([4,6,9,12]));
+ containsAllInOrder([4,6,9,12]),);
});
test('should not fail on deleting non existent intake', () {
final history = IntakeHistory([]);
history.deleteIntake(mockIntake(timeMs: 5));
final found = history.getIntakes(DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(0),
- end: DateTime.fromMillisecondsSinceEpoch(20)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(20),
+ ),);
expect(found.length, 0);
});
test('should serialize and deserialize', () {
test/model/medicine/medicine_intake_test.dart
@@ -31,19 +31,19 @@ void main() {
final intake2 = mockIntake(
timeMs: 543211,
dosis: 1000231,
- medicine: mockMedicine(designation: 'tst')
+ medicine: mockMedicine(designation: 'tst'),
);
expect(MedicineIntake.deserialize(
intake2.serialize(),
- [intake.medicine, intake2.medicine]),
- intake2);
+ [intake.medicine, intake2.medicine],),
+ intake2,);
});
test('should fail to deserialize serialized intake without exising med', () {
final intake = mockIntake(medicine: mockMedicine(designation: 'tst'));
expect(() => MedicineIntake.deserialize(
intake.serialize(),
- [mockMedicine()]),
- throwsStateError);
+ [mockMedicine()],),
+ throwsStateError,);
});
});
}
@@ -55,9 +55,9 @@ void main() {
MedicineIntake mockIntake({
double dosis = 0,
int? timeMs,
- Medicine? medicine
+ Medicine? medicine,
}) => MedicineIntake(
medicine: medicine ?? mockMedicine(),
dosis: dosis,
- timestamp: timeMs == null ? DateTime.now() : DateTime.fromMillisecondsSinceEpoch(timeMs)
+ timestamp: timeMs == null ? DateTime.now() : DateTime.fromMillisecondsSinceEpoch(timeMs),
);
\ No newline at end of file
test/model/analyzer_test.dart
@@ -6,10 +6,10 @@ import 'package:flutter_test/flutter_test.dart';
void main() {
group('BloodPressureAnalyser', () {
test('should return averages', () async {
- var m = BloodPressureAnalyser([
+ final m = BloodPressureAnalyser([
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(1), 122, 87, 65, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(2), 100, 60, 62, ''),
- BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(3), 111, 73, 73, '')
+ BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(3), 111, 73, 73, ''),
]);
expect(m.avgSys, 111);
@@ -18,11 +18,11 @@ void main() {
});
test('should return max', () async {
- var a = BloodPressureAnalyser([
+ final a = BloodPressureAnalyser([
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(1), 123, 87, 65, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(2), 100, 60, 62, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(3), 111, 73, 73, ''),
- BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(4), 111, 73, 73, '')
+ BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(4), 111, 73, 73, ''),
]);
expect(a.maxSys, 123);
@@ -31,11 +31,11 @@ void main() {
});
test('should return min', () async {
- var a = BloodPressureAnalyser([
+ final a = BloodPressureAnalyser([
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(1), 123, 87, 65, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(2), 100, 60, 62, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(3), 111, 73, 73, ''),
- BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(4), 100, 60, 62, '')
+ BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(4), 100, 60, 62, ''),
]);
expect(a.minSys, 100);
@@ -44,15 +44,15 @@ void main() {
});
test('should know count', () async {
- var m = BloodPressureAnalyser([
+ final m = BloodPressureAnalyser([
for (int i = 1; i < 101; i++)
- BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(i), 0, 0, 0, '')
+ BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(i), 0, 0, 0, ''),
]);
expect(m.count, 100);
});
test('should determine special days', () async {
- var m = BloodPressureAnalyser([BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(100), 0, 0, 0, ''),
+ final m = BloodPressureAnalyser([BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(100), 0, 0, 0, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(20), 0, 0, 0, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(9000000), 0, 0, 0, ''),
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(3124159), 0, 0, 0, ''),
test/model/bood_pressure_test.dart
@@ -9,18 +9,18 @@ import '../ram_only_implementations.dart';
void main() {
group('BloodPressureRecord', () {
test('should initialize with all values supported by dart', () {
- BloodPressureRecord record = BloodPressureRecord(DateTime.fromMicrosecondsSinceEpoch(1582991592), 0, -50, 1000,
- "((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა");
+ final BloodPressureRecord record = BloodPressureRecord(DateTime.fromMicrosecondsSinceEpoch(1582991592), 0, -50, 1000,
+ '((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა',);
expect(record.creationTime, DateTime.fromMicrosecondsSinceEpoch(1582991592));
expect(record.systolic, 0);
expect(record.diastolic, -50);
expect(record.pulse, 1000);
expect(record.notes,
- "((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა");
+ '((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა',);
});
test('should not save times at or before epoch', () {
- expect(() => BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(0), 0, 0, 0, ""), throwsAssertionError);
+ expect(() => BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(0), 0, 0, 0, ''), throwsAssertionError);
});
});
@@ -33,16 +33,16 @@ void main() {
test('should initialize', () async {
expect(() async {
await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldInit.db'));
- }, returnsNormally);
+ }, returnsNormally,);
});
test('should start empty', () async {
- var m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldStartEmpty.db'));
+ final m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldStartEmpty.db'));
expect((await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).length, 0);
});
test('should notify when adding entries', () async {
- var m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldNotifyWhenAdding.db'));
+ final m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldNotifyWhenAdding.db'));
int listenerCalls = 0;
m.addListener(() {
@@ -57,12 +57,12 @@ void main() {
});
test('should return entries as added', () async {
- var m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldReturnAddedEntries.db'));
+ final m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldReturnAddedEntries.db'));
- var r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
- "((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა");
+ final r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
+ '((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა',);
m.addListener(() async {
- var res = (await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
+ final res = (await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
expect(res, isNotNull);
expect(res.creationTime, r.creationTime);
expect(res.systolic, r.systolic);
@@ -76,13 +76,13 @@ void main() {
});
test('should save and load between objects/sessions', () async {
- var m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldPersist.db'));
- var r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
- "((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა");
+ final m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldPersist.db'));
+ final r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
+ '((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა',);
await m.add(r);
- var m2 = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldPersist.db'));
- var res = (await m2.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
+ final m2 = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldPersist.db'));
+ final res = (await m2.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
expect(res.creationTime, r.creationTime);
expect(res.systolic, r.systolic);
@@ -92,7 +92,7 @@ void main() {
});
test('should delete', () async {
- var m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldDelete.db'));
+ final m = await BloodPressureModel.create(dbPath: join(inMemoryDatabasePath, 'BPMShouldDelete.db'));
await m.add(BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(758934), 123, 87, 65, ';)'));
expect((await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).length, 1);
@@ -105,18 +105,18 @@ void main() {
});
});
- group("RamBloodPressureModel should behave like BloodPressureModel", () {
+ group('RamBloodPressureModel should behave like BloodPressureModel', () {
test('should initialize', () async {
expect(() async => RamBloodPressureModel(), returnsNormally);
});
test('should start empty', () async {
- var m = RamBloodPressureModel();
+ final m = RamBloodPressureModel();
expect((await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).length, 0);
});
test('should notify when adding entries', () async {
- var m = RamBloodPressureModel();
+ final m = RamBloodPressureModel();
int listenerCalls = 0;
m.addListener(() {
@@ -131,12 +131,12 @@ void main() {
});
test('should return entries as added', () async {
- var m = RamBloodPressureModel();
+ final m = RamBloodPressureModel();
- var r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
- "((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა");
+ final r = BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31415926), -172, 10000, 0,
+ '((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈๏ แผ่นดินฮั่นเABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ–—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвг, \n \t д∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა',);
m.addListener(() async {
- var res = (await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
+ final res = (await m.getInTimeRange(DateTime.fromMillisecondsSinceEpoch(1), DateTime.now())).first;
expect(res, isNotNull);
expect(res.creationTime, r.creationTime);
expect(res.systolic, r.systolic);
test/model/intervall_store_test.dart
@@ -8,8 +8,8 @@ void main() {
test('base constructor should initialize with values', () {
final storageObject = IntervallStorage(stepSize: TimeStep.month, range: DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(1234),
- end: DateTime.fromMillisecondsSinceEpoch(5678)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(5678),
+ ),);
expect(storageObject.stepSize, TimeStep.month);
expect(storageObject.currentRange.start.millisecondsSinceEpoch, 1234);
@@ -21,7 +21,7 @@ void main() {
expect(storageObject.stepSize, TimeStep.last7Days);
expect(storageObject.currentRange.start.millisecondsSinceEpoch, lessThanOrEqualTo(DateTime
.now()
- .millisecondsSinceEpoch));
+ .millisecondsSinceEpoch,),);
});
test('base constructor should initialize with only incomplete parameters', () {
@@ -29,8 +29,8 @@ void main() {
IntervallStorage(stepSize: TimeStep.last30Days);
IntervallStorage(range: DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(1234),
- end: DateTime.fromMillisecondsSinceEpoch(5678)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(5678),
+ ),);
});
@@ -59,8 +59,8 @@ void main() {
final last30DaysIntervall = IntervallStorage(stepSize: TimeStep.last30Days);
final customIntervall = IntervallStorage(stepSize: TimeStep.custom, range: DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(1234),
- end: DateTime.fromMillisecondsSinceEpoch(1234 + 24 * 60 * 60 * 1000) // one day
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(1234 + 24 * 60 * 60 * 1000), // one day
+ ),);
expect(customIntervall.currentRange.duration.inMilliseconds, 24 * 60 * 60 * 1000);
test/model/json_serialization_test.dart
@@ -28,16 +28,16 @@ void main() {
expect(initialData.stepSize, recreatedData.stepSize);
expect(initialData.currentRange.start.millisecondsSinceEpoch,
- recreatedData.currentRange.start.millisecondsSinceEpoch);
+ recreatedData.currentRange.start.millisecondsSinceEpoch,);
expect(initialData.currentRange.end.millisecondsSinceEpoch,
- recreatedData.currentRange.end.millisecondsSinceEpoch);
+ recreatedData.currentRange.end.millisecondsSinceEpoch,);
});
test('should load same data from json in edge cases', () {
final initialData = IntervallStorage(stepSize: TimeStep.month, range: DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(1234),
- end: DateTime.fromMillisecondsSinceEpoch(5678)
- ));
+ end: DateTime.fromMillisecondsSinceEpoch(5678),
+ ),);
final json = initialData.toJson();
final recreatedData = IntervallStorage.fromJson(json);
test/ui/components/settings/color_picker_list_tile_test.dart
@@ -13,7 +13,7 @@ void main() {
onMainColorChanged: (Color value) {
assert(false, 'should not be called');
},
- initialColor: Colors.teal,)));
+ initialColor: Colors.teal,),),);
expect(widgetTester.takeException(), isNull);
});
testWidgets('should preview color', (widgetTester) async {
@@ -22,11 +22,11 @@ void main() {
onMainColorChanged: (Color value) {
assert(false, 'should not be called');
},
- initialColor: Colors.teal,)));
+ initialColor: Colors.teal,),),);
expect(find.byType(CircleAvatar), findsOneWidget);
expect(widgetTester.widget(find.byType(CircleAvatar)), isA<CircleAvatar>().having(
- (p0) => p0.backgroundColor, 'display color', Colors.teal));
+ (p0) => p0.backgroundColor, 'display color', Colors.teal,),);
});
testWidgets('should show colorPicker on tap', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(ColorSelectionListTile(
@@ -34,7 +34,7 @@ void main() {
onMainColorChanged: (Color value) {
assert(false, 'should not be called');
},
- initialColor: Colors.teal,)));
+ initialColor: Colors.teal,),),);
expect(find.byType(ColorPicker), findsNothing);
await widgetTester.tap(find.byType(ListTile));
@@ -49,7 +49,7 @@ void main() {
callCount += 1;
expect(value, Colors.red);
},
- initialColor: Colors.teal,)));
+ initialColor: Colors.teal,),),);
expect(find.byType(ColorPicker), findsNothing);
await widgetTester.tap(find.byType(ListTile));
@@ -68,7 +68,7 @@ void main() {
onMainColorChanged: (Color value) {
assert(false, 'should not be called');
},
- initialColor: Colors.transparent,)));
+ initialColor: Colors.transparent,),),);
expect(find.byType(CircleAvatar), findsNothing);
});
@@ -76,9 +76,7 @@ void main() {
}
/// Finds the widget with a specific color inside a [ColorPicker], when put into a [CommonFinders.byElementPredicate].
-bool Function(Element e) findColored(Color color) {
- return (e) =>
+bool Function(Element e) findColored(Color color) => (e) =>
e.widget is Container &&
(e.widget as Container).decoration is BoxDecoration &&
((e.widget as Container).decoration as BoxDecoration).color == color;
-}
test/ui/components/settings/dropdown_list_tile_test.dart
@@ -14,10 +14,10 @@ void main() {
},
items: [
for (int i = 0; i < 10; i++)
- DropdownMenuItem(value: i, child: Text('option $i'))
+ DropdownMenuItem(value: i, child: Text('option $i')),
],
value: 3,
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
await widgetTester.pumpWidget(materialApp(DropDownListTile<int>(
title: const Text('This is a very long test title.'),
@@ -28,10 +28,10 @@ void main() {
},
items: [
for (int i = 0; i < 1000; i++)
- DropdownMenuItem(value: i, child: Text('option $i'))
+ DropdownMenuItem(value: i, child: Text('option $i')),
],
value: 527,
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
});
testWidgets('should display selected option', (widgetTester) async {
@@ -42,10 +42,10 @@ void main() {
},
items: [
for (int i = 0; i < 10; i++)
- DropdownMenuItem(value: i, child: Text('option $i'))
+ DropdownMenuItem(value: i, child: Text('option $i')),
],
value: 3,
- )));
+ ),),);
expect(find.text('option 3'), findsOneWidget);
expect(find.text('option 4'), findsNothing);
});
@@ -59,10 +59,10 @@ void main() {
},
items: [
for (int i = 0; i < 10; i++)
- DropdownMenuItem(value: i, child: Text('option $i'))
+ DropdownMenuItem(value: i, child: Text('option $i')),
],
value: 3,
- )));
+ ),),);
await widgetTester.tap(find.text('option 3'));
await widgetTester.pumpAndSettle();
test/ui/components/settings/input_list_tile_test.dart
@@ -14,7 +14,7 @@ void main() {
onSubmit: (String newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
expect(find.text('test title'), findsOneWidget);
expect(find.text('initial'), findsOneWidget);
@@ -26,7 +26,7 @@ void main() {
onSubmit: (String newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(find.byType(InputDialoge), findsNothing);
await widgetTester.tap(find.byType(InputListTile));
@@ -45,7 +45,7 @@ void main() {
onSubmit: (String newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(find.text('initial'), findsOneWidget);
await widgetTester.tap(find.byType(InputListTile));
@@ -62,7 +62,7 @@ void main() {
callCount += 1;
expect(newValue, 'changed');
},
- )));
+ ),),);
expect(find.text('initial'), findsOneWidget);
await widgetTester.tap(find.byType(InputListTile));
test/ui/components/settings/number_input_list_tile_test.dart
@@ -14,7 +14,7 @@ void main() {
onParsableSubmit: (double newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
expect(find.text('test title'), findsOneWidget);
expect(find.text('15'), findsOneWidget);
@@ -26,7 +26,7 @@ void main() {
onParsableSubmit: (double newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(find.byType(InputDialoge), findsNothing);
await widgetTester.tap(find.byType(NumberInputListTile));
@@ -45,7 +45,7 @@ void main() {
onParsableSubmit: (double newValue) {
assert(false, 'should not be called');
},
- )));
+ ),),);
expect(find.text('15'), findsOneWidget);
await widgetTester.tap(find.byType(NumberInputListTile));
@@ -75,7 +75,7 @@ void main() {
break;
}
},
- )));
+ ),),);
expect(find.text('15'), findsOneWidget);
await widgetTester.tap(find.byType(NumberInputListTile));
test/ui/components/settings/slider_list_tile_test.dart
@@ -15,7 +15,7 @@ void main() {
value: 15,
min: 1,
max: 20,
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
await widgetTester.pumpWidget(materialApp(SliderListTile(
title: const Text('Very long title that could overflow'),
@@ -29,7 +29,7 @@ void main() {
leading: const Icon(Icons.add),
trailing: const Icon(Icons.add),
subtitle: const Text('While sliders support subtitle widgets, they should not interfere with the slider!'),
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
});
testWidgets('should report value changes', (widgetTester) async {
@@ -44,7 +44,7 @@ void main() {
min: 1,
max: 10,
subtitle: const Text('While sliders support subtitle widgets, they should not interfere with the slider!'),
- )));
+ ),),);
final topLeft = widgetTester.getTopLeft(find.byType(Slider));
final bottomRight = widgetTester.getBottomRight(find.byType(Slider));
test/ui/components/settings/titled_column_test.dart
@@ -13,10 +13,10 @@ void main() {
const ListTile(title: Text('ListTile text 1'),),
SwitchListTile(
title: const Text('SwitchListTile text'),
- value: true, onChanged: (v) {}),
+ value: true, onChanged: (v) {},),
const ListTile(title: Text('ListTile text 2'),),
],
- )));
+ ),),);
expect(widgetTester.takeException(), isNull);
expect(find.text('test title'), findsOneWidget);
@@ -31,16 +31,16 @@ void main() {
const ListTile(title: Text('ListTile text 1'),),
SwitchListTile(
title: const Text('SwitchListTile text'),
- value: true, onChanged: (v) {}),
+ value: true, onChanged: (v) {},),
const ListTile(title: Text('ListTile text 2'),),
],
- )));
+ ),),);
expect(find.byType(Column), findsOneWidget);
expect(find.descendant(
of: find.byType(Column).first,
- matching: find.text('test title')),
- findsOneWidget
+ matching: find.text('test title'),),
+ findsOneWidget,
);
});
});
test/ui/components/add_export_column_dialoge_test.dart
@@ -27,8 +27,8 @@ void main() {
});
testWidgets('should prefill values', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(
- AddExportColumnDialoge(initialColumn: UserColumn('id', 'csvTitle', r'formatPattern$SYS'), settings: Settings(),)
- ));
+ AddExportColumnDialoge(initialColumn: UserColumn('id', 'csvTitle', r'formatPattern$SYS'), settings: Settings(),),
+ ),);
expect(widgetTester.takeException(), isNull);
expect(find.text('SAVE'), findsOneWidget);
@@ -43,8 +43,8 @@ void main() {
});
testWidgets('should show preview', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(
- AddExportColumnDialoge(initialColumn: UserColumn('id', 'csvTitle', r'formatPattern$SYS'), settings: Settings(),)
- ));
+ AddExportColumnDialoge(initialColumn: UserColumn('id', 'csvTitle', r'formatPattern$SYS'), settings: Settings(),),
+ ),);
await widgetTester.pumpAndSettle();
expect(find.text('Please enter a value'), findsNothing);
@@ -91,16 +91,16 @@ void main() {
expect(returnedValue, false);
expect(find.ancestor(of: find.text(localizations.csvTitle).first, matching: find.byType(TextFormField)),
- findsAtLeastNWidgets(1));
+ findsAtLeastNWidgets(1),);
await widgetTester.enterText(
find.ancestor(of: find.text(localizations.csvTitle).first, matching: find.byType(TextFormField)),
- 'testCsvTitle');
+ 'testCsvTitle',);
expect(find.ancestor(of: find.text(localizations.csvTitle).first, matching: find.byType(TextFormField)),
- findsAtLeastNWidgets(1));
+ findsAtLeastNWidgets(1),);
await widgetTester.enterText(
find.ancestor(of: find.text(localizations.fieldFormat).first, matching: find.byType(TextFormField)),
- r'test$SYSformat');
+ r'test$SYSformat',);
expect(find.text(localizations.btnSave), findsOneWidget);
await widgetTester.tap(find.text(localizations.btnSave));
@@ -109,7 +109,7 @@ void main() {
expect(find.byType(AddExportColumnDialoge), findsNothing);
expect(returnedValue, isA<UserColumn>()
.having((p0) => p0.csvTitle, 'csvTitle', 'testCsvTitle')
- .having((p0) => p0.formatter.formatPattern, 'formatter', r'test$SYSformat'));
+ .having((p0) => p0.formatter.formatPattern, 'formatter', r'test$SYSformat'),);
});
testWidgets('should keep internalIdentifier on edit', (widgetTester) async {
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
@@ -117,16 +117,16 @@ void main() {
dynamic returnedValue = false;
await loadDialoge(widgetTester, (context) async => returnedValue =
await showAddExportColumnDialoge(context, Settings(),
- UserColumn('initialInternalIdentifier', 'csvTitle', 'formatPattern')
- ));
+ UserColumn('initialInternalIdentifier', 'csvTitle', 'formatPattern'),
+ ),);
expect(returnedValue, false);
expect(find.ancestor(of: find.text(localizations.csvTitle).first, matching: find.byType(TextFormField)),
- findsAtLeastNWidgets(1));
+ findsAtLeastNWidgets(1),);
await widgetTester.enterText(
find.ancestor(of: find.text(localizations.csvTitle).first, matching: find.byType(TextFormField)),
- 'changedCsvTitle');
+ 'changedCsvTitle',);
expect(find.text(localizations.btnSave), findsOneWidget);
await widgetTester.tap(find.text(localizations.btnSave));
@@ -134,7 +134,7 @@ void main() {
expect(find.byType(AddExportColumnDialoge), findsNothing);
expect(returnedValue, isA<UserColumn>()
- .having((p0) => p0.internalIdentifier, 'identifier', 'userColumn.initialInternalIdentifier'));
+ .having((p0) => p0.internalIdentifier, 'identifier', 'userColumn.initialInternalIdentifier'),);
});
});
test/ui/components/add_measurement_dialoge_test.dart
@@ -21,8 +21,8 @@ void main() {
await widgetTester.pumpWidget(materialApp(
AddEntryDialoge(
settings: Settings(),
- )
- ));
+ ),
+ ),);
expect(widgetTester.takeException(), isNull);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
@@ -39,10 +39,10 @@ void main() {
settings: Settings(),
initialRecord: BloodPressureRecord(
DateTime.now(), 123, 56, 43, 'Test note',
- needlePin: const MeasurementNeedlePin(Colors.teal)
+ needlePin: const MeasurementNeedlePin(Colors.teal),
),
- )
- ));
+ ),
+ ),);
await widgetTester.pumpAndSettle();
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
expect(find.text('SAVE'), findsOneWidget);
@@ -53,16 +53,16 @@ void main() {
expect(find.text('43'), findsOneWidget);
expect(find.byType(ColorSelectionListTile), findsOneWidget);
expect(find.byType(ColorSelectionListTile).evaluate().first.widget, isA<ColorSelectionListTile>().
- having((p0) => p0.initialColor, 'ColorSelectionListTile should have correct initial color', Colors.teal));
+ having((p0) => p0.initialColor, 'ColorSelectionListTile should have correct initial color', Colors.teal),);
});
testWidgets('should show medication picker when medications available', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(
AddEntryDialoge(
settings: Settings(
- medications: [mockMedicine(designation: 'testmed')]
+ medications: [mockMedicine(designation: 'testmed')],
),
- )
- ));
+ ),
+ ),);
await widgetTester.pumpAndSettle();
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
@@ -79,10 +79,10 @@ void main() {
await widgetTester.pumpWidget(materialApp(
AddEntryDialoge(
settings: Settings(
- medications: [mockMedicine(designation: 'testmed')]
+ medications: [mockMedicine(designation: 'testmed')],
),
- )
- ));
+ ),
+ ),);
await widgetTester.pumpAndSettle();
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
@@ -101,7 +101,7 @@ void main() {
expect(
find.ancestor(
of: find.text(localizations.dosis,).first,
- matching: find.byType(TextFormField)
+ matching: find.byType(TextFormField),
),
findsOneWidget,
);
@@ -110,10 +110,10 @@ void main() {
await widgetTester.pumpWidget(materialApp(
AddEntryDialoge(
settings: Settings(
- medications: [mockMedicine(designation: 'testmed', defaultDosis: 3.1415)]
+ medications: [mockMedicine(designation: 'testmed', defaultDosis: 3.1415)],
),
- )
- ));
+ ),
+ ),);
await widgetTester.pumpAndSettle();
await widgetTester.tap(find.byType(DropdownButton<Medicine?>));
@@ -130,7 +130,7 @@ void main() {
dynamic result = 'result before save';
await loadDialoge(widgetTester, (context) async
=> result = await showAddEntryDialoge(context, Settings(),
- mockRecord(sys: 123, dia: 56, pul: 43, note: 'Test note', pin: Colors.teal)));
+ mockRecord(sys: 123, dia: 56, pul: 43, note: 'Test note', pin: Colors.teal),),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
expect(find.byType(AddEntryDialoge), findsOneWidget);
@@ -144,7 +144,7 @@ void main() {
dynamic result = 'result before save';
final record = mockRecord(sys: 123, dia: 56, pul: 43, note: 'Test note', pin: Colors.teal);
await loadDialoge(widgetTester, (context) async
- => result = await showAddEntryDialoge(context, Settings(), record));
+ => result = await showAddEntryDialoge(context, Settings(), record),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
expect(find.byType(AddEntryDialoge), findsOneWidget);
@@ -156,12 +156,12 @@ void main() {
expect(result?.$1, isA<BloodPressureRecord>().having(
(p0) => (p0.creationTime, p0.systolic, p0.diastolic, p0.pulse, p0.notes, p0.needlePin!.color),
'should return initial values as they were not modified',
- (record.creationTime, record.systolic, record.diastolic, record.pulse, record.notes, record.needlePin!.color)));
+ (record.creationTime, record.systolic, record.diastolic, record.pulse, record.notes, record.needlePin!.color),),);
});
testWidgets('should be able to input records', (WidgetTester widgetTester) async {
dynamic result = 'result before save';
await loadDialoge(widgetTester, (context) async
- => result = await showAddEntryDialoge(context, Settings()));
+ => result = await showAddEntryDialoge(context, Settings()),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
await widgetTester.enterText(find.ancestor(of: find.text('Systolic').first, matching: find.byType(TextFormField)), '123');
@@ -184,22 +184,22 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', 67)
.having((p0) => p0.pulse, 'pulse', 89)
.having((p0) => p0.notes, 'notes', 'Test note')
- .having((p0) => p0.needlePin?.color, 'needlePin', Colors.red)
+ .having((p0) => p0.needlePin?.color, 'needlePin', Colors.red),
);
});
testWidgets('should allow value only', (WidgetTester widgetTester) async {
dynamic result = 'result before save';
await loadDialoge(widgetTester, (context) async
- => result = await showAddEntryDialoge(context, Settings()));
+ => result = await showAddEntryDialoge(context, Settings()),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
await widgetTester.enterText(find.ancestor(of: find.text(localizations.sysLong).first,
- matching: find.byType(TextFormField)), '123');
+ matching: find.byType(TextFormField),), '123',);
await widgetTester.enterText(find.ancestor(of: find.text(localizations.diaLong).first,
- matching: find.byType(TextFormField)), '67');
+ matching: find.byType(TextFormField),), '67',);
await widgetTester.enterText(find.ancestor(of: find.text(localizations.pulLong).first,
- matching: find.byType(TextFormField)), '89');
+ matching: find.byType(TextFormField),), '89',);
expect(find.text(localizations.btnSave), findsOneWidget);
await widgetTester.tap(find.text(localizations.btnSave));
@@ -211,7 +211,7 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', 67)
.having((p0) => p0.pulse, 'pulse', 89)
.having((p0) => p0.notes, 'notes', '')
- .having((p0) => p0.needlePin?.color, 'needlePin', null)
+ .having((p0) => p0.needlePin?.color, 'needlePin', null),
);
});
testWidgets('should allow note only', (WidgetTester widgetTester) async {
@@ -219,13 +219,13 @@ void main() {
await loadDialoge(widgetTester, (context) async
=> result = await showAddEntryDialoge(context, Settings(
allowMissingValues: true,
- validateInputs: false
- )));
+ validateInputs: false,
+ ),),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
await widgetTester.enterText(find.ancestor(of: find.text(localizations.addNote).first,
- matching: find.byType(TextFormField)), 'test note');
+ matching: find.byType(TextFormField),), 'test note',);
expect(find.text(localizations.btnSave), findsOneWidget);
await widgetTester.tap(find.text(localizations.btnSave));
@@ -237,7 +237,7 @@ void main() {
.having((p0) => p0.diastolic, 'diastolic', null)
.having((p0) => p0.pulse, 'pulse', null)
.having((p0) => p0.notes, 'notes', 'test note')
- .having((p0) => p0.needlePin?.color, 'needlePin', null)
+ .having((p0) => p0.needlePin?.color, 'needlePin', null),
);
});
testWidgets('should be able to input medicines', (WidgetTester widgetTester) async {
@@ -249,8 +249,8 @@ void main() {
medications: [
mockMedicine(designation: 'medication1'),
med2,
- ]
- )));
+ ],
+ ),),);
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
await widgetTester.tap(find.byType(DropdownButton<Medicine?>));
@@ -265,9 +265,9 @@ void main() {
await widgetTester.enterText(
find.ancestor(
of: find.text(localizations.dosis).first,
- matching: find.byType(TextFormField)
+ matching: find.byType(TextFormField),
),
- '123.456'
+ '123.456',
);
expect(find.text(localizations.btnSave), findsOneWidget);
@@ -278,7 +278,7 @@ void main() {
expect(result?.$2, isA<MedicineIntake>()
.having((p0) => p0.timestamp.millisecondsSinceEpoch ~/ 1000, 'timestamp', openDialogeTimeStamp.millisecondsSinceEpoch ~/ 1000)
.having((p0) => p0.medicine, 'medicine', med2)
- .having((p0) => p0.dosis, 'dosis', 123.456)
+ .having((p0) => p0.dosis, 'dosis', 123.456),
);
});
testWidgets('should not allow invalid values', (widgetTester) async {
@@ -346,7 +346,7 @@ void main() {
});
testWidgets('should allow invalid values when setting is set', (widgetTester) async {
await loadDialoge(widgetTester, (context) =>
- showAddEntryDialoge(context, Settings(validateInputs: false, allowMissingValues: true)));
+ showAddEntryDialoge(context, Settings(validateInputs: false, allowMissingValues: true)),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
await widgetTester.enterText(find.ancestor(of: find.text('Systolic').first, matching: find.byType(TextFormField)), '2');
@@ -357,14 +357,14 @@ void main() {
});
testWidgets('should respect settings.allowManualTimeInput', (widgetTester) async {
await loadDialoge(widgetTester, (context) =>
- showAddEntryDialoge(context, Settings(allowManualTimeInput: false)));
+ showAddEntryDialoge(context, Settings(allowManualTimeInput: false)),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
expect(find.byIcon(Icons.edit), findsNothing);
});
testWidgets('should start with sys input focused', (widgetTester) async {
await loadDialoge(widgetTester, (context) =>
- showAddEntryDialoge(context, Settings(), mockRecord(sys: 12)));
+ showAddEntryDialoge(context, Settings(), mockRecord(sys: 12)),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
final primaryFocus = FocusManager.instance.primaryFocus;
@@ -375,11 +375,11 @@ void main() {
);
expect(focusedTextFormField, findsOneWidget);
expect(focusedTextFormField.evaluate().first.widget, isA<TextFormField>()
- .having((p0) => p0.initialValue, 'systolic content', '12'));
+ .having((p0) => p0.initialValue, 'systolic content', '12'),);
});
testWidgets('should focus next on input finished', (widgetTester) async {
await loadDialoge(widgetTester, (context) =>
- showAddEntryDialoge(context, Settings(), mockRecord(sys: 12, dia: 3, pul: 4, note: 'note')));
+ showAddEntryDialoge(context, Settings(), mockRecord(sys: 12, dia: 3, pul: 4, note: 'note')),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
await widgetTester.enterText(find.ancestor(of: find.text('Systolic').first, matching: find.byType(TextFormField)), '123');
@@ -392,7 +392,7 @@ void main() {
);
expect(focusedTextFormField, findsOneWidget);
expect(focusedTextFormField.evaluate().first.widget, isA<TextFormField>()
- .having((p0) => p0.initialValue, 'diastolic content', '3'));
+ .having((p0) => p0.initialValue, 'diastolic content', '3'),);
await widgetTester.enterText(find.ancestor(of: find.text('Diastolic').first, matching: find.byType(TextFormField)), '78');
@@ -404,7 +404,7 @@ void main() {
);
expect(secondFocusedTextFormField, findsOneWidget);
expect(secondFocusedTextFormField.evaluate().first.widget, isA<TextFormField>()
- .having((p0) => p0.initialValue, 'pulse content', '4'));
+ .having((p0) => p0.initialValue, 'pulse content', '4'),);
await widgetTester.enterText(find.ancestor(of: find.text('Pulse').first, matching: find.byType(TextFormField)), '60');
@@ -416,12 +416,12 @@ void main() {
);
expect(thirdFocusedTextFormField, findsOneWidget);
expect(thirdFocusedTextFormField.evaluate().first.widget, isA<TextFormField>()
- .having((p0) => p0.initialValue, 'note input content', 'note'));
+ .having((p0) => p0.initialValue, 'note input content', 'note'),);
});
testWidgets('should focus last input field on backspace pressed in empty input field', (widgetTester) async {
await loadDialoge(widgetTester, (context) =>
- showAddEntryDialoge(context, Settings(), mockRecord(sys: 12, dia: 3, pul: 4, note: 'note')));
+ showAddEntryDialoge(context, Settings(), mockRecord(sys: 12, dia: 3, pul: 4, note: 'note')),);
expect(find.byType(DropdownButton<Medicine?>), findsNothing, reason: 'No medication in settings.');
await widgetTester.enterText(find.ancestor(of: find.text('note').first, matching: find.byType(TextFormField)), '');
test/ui/components/color_picker_test.dart
@@ -12,7 +12,7 @@ void main() {
await widgetTester.pumpWidget(materialApp(ColorPicker(showTransparentColor: false, onColorSelected: (color) {})));
await widgetTester.pumpWidget(materialApp(ColorPicker(circleSize: 15, onColorSelected: (color) {})));
await widgetTester.pumpWidget(
- materialApp(ColorPicker(availableColors: const [], initialColor: Colors.red, onColorSelected: (color) {})));
+ materialApp(ColorPicker(availableColors: const [], initialColor: Colors.red, onColorSelected: (color) {})),);
expect(widgetTester.takeException(), isNull);
});
testWidgets('should report correct picked color', (widgetTester) async {
@@ -20,7 +20,7 @@ void main() {
await widgetTester.pumpWidget(materialApp(ColorPicker(onColorSelected: (color) {
expect(color, Colors.blue);
onColorSelectedCallCount += 1;
- })));
+ },),),);
final containers = find.byType(Container).evaluate();
final blueColor = containers.where((element) { // find widgets with color blue
test/ui/components/enter_timeformat_dialoge_test.dart
@@ -21,8 +21,8 @@ void main() {
await widgetTester.pumpWidget(materialApp(EnterTimeFormatDialoge(
initialValue: 'yyyy-MM-dd HH:mm',
previewTime: DateTime(2023, 7, 23, 8, 20),
- )
- ));
+ ),
+ ),);
expect(find.text('2023-07-23 08:20'), findsOneWidget);
// other time formats
@@ -57,7 +57,7 @@ void main() {
testWidgets('should return null on close', (widgetTester) async {
String? result = 'notnull';
await loadDialoge(widgetTester,
- (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false));
+ (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false),);
expect(find.byIcon(Icons.close), findsOneWidget);
await widgetTester.tap(find.byIcon(Icons.close));
@@ -68,7 +68,7 @@ void main() {
testWidgets('should return value on save', (widgetTester) async {
String? result;
await loadDialoge(widgetTester,
- (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false));
+ (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false),);
expect(find.text('SAVE'), findsOneWidget);
await widgetTester.tap(find.text('SAVE'));
@@ -79,7 +79,7 @@ void main() {
testWidgets('should return modified value on save', (widgetTester) async {
String? result;
await loadDialoge(widgetTester,
- (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false));
+ (context) async => result = await showTimeFormatPickerDialoge(context, 'yyyy-MM-dd HH:mm', false),);
await widgetTester.enterText(find.byType(TextField), 'test text!');
await widgetTester.pumpAndSettle();
test/ui/components/input_dialoge_test.dart
@@ -15,8 +15,8 @@ void main() {
home: InputDialoge(
hintText: 'test hint',
initialValue: 'initial text',
- )
- ));
+ ),
+ ),);
expect(widgetTester.takeException(), isNull);
expect(find.byType(InputDialoge), findsOneWidget);
});
@@ -24,7 +24,7 @@ void main() {
await widgetTester.pumpWidget(materialApp(const InputDialoge(
hintText: 'test hint',
initialValue: 'initial text',
- )));
+ ),),);
expect(find.text('initial text'), findsOneWidget);
expect(find.text('test hint'), findsNWidgets(2));
});
@@ -32,7 +32,7 @@ void main() {
await widgetTester.pumpWidget(materialApp(InputDialoge(
initialValue: 'initial text',
validator: (_) => 'test error',
- )));
+ ),),);
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
expect(find.text(localizations.btnConfirm), findsOneWidget);
@@ -51,7 +51,7 @@ void main() {
validatorCalls += 1;
return null;
},
- )));
+ ),),);
final localizations = await AppLocalizations.delegate.load(const Locale('en'));
expect(validatorCalls, 0);
test/ui/components/measurement_list_entry_test.dart
@@ -13,21 +13,21 @@ void main() {
testWidgets('should initialize without errors', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
settings: Settings(),
- record: BloodPressureRecord(DateTime(2023), 123, 80, 60, 'test'))));
+ record: BloodPressureRecord(DateTime(2023), 123, 80, 60, 'test'),),),);
expect(widgetTester.takeException(), isNull);
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
settings: Settings(),
- record: BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31279811), null, null, null, 'null test'))));
+ record: BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(31279811), null, null, null, 'null test'),),),);
expect(widgetTester.takeException(), isNull);
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
settings: Settings(),
- record: BloodPressureRecord(DateTime(2023), 124, 85, 63, 'color', needlePin: const MeasurementNeedlePin(Colors.cyan)))));
+ record: BloodPressureRecord(DateTime(2023), 124, 85, 63, 'color', needlePin: const MeasurementNeedlePin(Colors.cyan)),),),);
expect(widgetTester.takeException(), isNull);
});
testWidgets('should expand correctly', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
settings: Settings(),
- record: BloodPressureRecord(DateTime(2023), 123, 78, 56, 'Test texts'))));
+ record: BloodPressureRecord(DateTime(2023), 123, 78, 56, 'Test texts'),),),);
expect(find.byIcon(Icons.expand_more), findsOneWidget);
await widgetTester.tap(find.byIcon(Icons.expand_more));
await widgetTester.pumpAndSettle();
@@ -38,7 +38,7 @@ void main() {
testWidgets('should display correct information', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
settings: Settings(),
- record: BloodPressureRecord(DateTime(2023), 123, 78, 56, 'Test text'))));
+ record: BloodPressureRecord(DateTime(2023), 123, 78, 56, 'Test text'),),),);
expect(find.text('123'), findsOneWidget);
expect(find.text('78'), findsOneWidget);
expect(find.text('56'), findsOneWidget);
@@ -54,7 +54,7 @@ void main() {
});
testWidgets('should not display null values', (widgetTester) async {
await widgetTester.pumpWidget(materialApp(MeasurementListRow(
- settings: Settings(), record: mockRecord(time: DateTime(2023)))));
+ settings: Settings(), record: mockRecord(time: DateTime(2023)),),),);
expect(find.text('null'), findsNothing);
expect(find.byIcon(Icons.expand_more), findsOneWidget);
await widgetTester.tap(find.byIcon(Icons.expand_more));
test/ui/components/util.dart
@@ -3,13 +3,11 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
-Widget materialApp(Widget child) {
- return MaterialApp(
+Widget materialApp(Widget child) => MaterialApp(
localizationsDelegates: const [AppLocalizations.delegate,],
locale: const Locale('en'),
home: Scaffold(body:child),
);
-}
/// Open a dialoge through a button press.
///
@@ -23,7 +21,7 @@ Widget materialApp(Widget child) {
/// ```
Future<void> loadDialoge(WidgetTester tester, void Function(BuildContext context) dialogeStarter, { String dialogeStarterText = 'X' }) async {
await tester.pumpWidget(materialApp(Builder(builder: (context) =>
- TextButton(onPressed: () => dialogeStarter(context), child: Text(dialogeStarterText)))));
+ TextButton(onPressed: () => dialogeStarter(context), child: Text(dialogeStarterText)),),),);
await tester.tap(find.text(dialogeStarterText));
await tester.pumpAndSettle();
}
\ No newline at end of file
test/ui/statistics_test.dart
@@ -14,18 +14,18 @@ import 'package:provider/provider.dart';
import '../ram_only_implementations.dart';
void main() {
- group("StatisticsPage", () {
+ group('StatisticsPage', () {
testWidgets('should load page', (widgetTester) async {
await _initStatsPage(widgetTester, []);
expect(widgetTester.takeException(), isNull);
expect(find.text('Statistics'), findsOneWidget);
});
- testWidgets("should report measurement count", (widgetTester) async {
+ testWidgets('should report measurement count', (widgetTester) async {
await _initStatsPage(widgetTester, [
for (int i = 1; i<51; i++) // can't safe entries at or before epoch
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(1582991592 + i), 40+i, 60+i, 30+i, 'Test comment $i'),
],
- intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime))
+ intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime)),
);
final measurementCountWidget = find.byKey(const Key('measurementCount'));
expect(measurementCountWidget, findsOneWidget);
@@ -40,14 +40,14 @@ void main() {
for (int i = 1; i<51; i++) // can't safe entries at or before epoch
BloodPressureRecord(DateTime.fromMillisecondsSinceEpoch(1582991592 + i), 40+i, 60+i, 30+i, 'Test comment $i'),
],
- intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime))
+ intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime)),
);
expect(find.text('null',findRichText: true, skipOffstage: false), findsNothing);
});
testWidgets("should not display 'null' when empty", (widgetTester) async {
await _initStatsPage(widgetTester, [],
- intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime))
+ intervallStoreManager: IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage(stepSize: TimeStep.lifetime)),
);
expect(find.text('null',findRichText: true, skipOffstage: false), findsNothing);
});
@@ -68,7 +68,7 @@ Future<void> _initStatsPage(WidgetTester widgetTester, List<BloodPressureRecord>
pdfExportSettings ??= PdfExportSettings();
intervallStoreManager ??= IntervallStoreManager(IntervallStorage(), IntervallStorage(), IntervallStorage());
- for (var r in records) {
+ for (final r in records) {
model.add(r);
}
@@ -85,7 +85,7 @@ Future<void> _initStatsPage(WidgetTester widgetTester, List<BloodPressureRecord>
delegates: AppLocalizations.localizationsDelegates,
locale: const Locale('en'),
child: const StatisticsPage(),
- )
- ));
+ ),
+ ),);
await widgetTester.pumpAndSettle();
}
\ No newline at end of file
test/ram_only_implementations.dart
@@ -9,7 +9,7 @@ class RamBloodPressureModel extends ChangeNotifier implements BloodPressureModel
static RamBloodPressureModel fromEntries(List<BloodPressureRecord> records) {
final m = RamBloodPressureModel();
- for (var e in records) {
+ for (final e in records) {
m.add(e);
}
return m;
@@ -28,7 +28,7 @@ class RamBloodPressureModel extends ChangeNotifier implements BloodPressureModel
@override
Future<UnmodifiableListView<BloodPressureRecord>> getInTimeRange(DateTime from, DateTime to) async {
- List<BloodPressureRecord> recordsInTime = [];
+ final List<BloodPressureRecord> recordsInTime = [];
for (final e in _records) {
if (e.creationTime.isAfter(from) && e.creationTime.isBefore(to)) {
recordsInTime.add(e);