feat: basic trainer support

This commit is contained in:
2026-11-24 20:02:05 +01:00
parent 30b25784c1
commit 9dece10e29
17 changed files with 3048 additions and 58 deletions

View File

@ -1,9 +1,17 @@
import 'dart:async';
import 'package:abawo_bt_app/model/shifter_types.dart';
import 'package:abawo_bt_app/model/trainer_model.dart';
import 'package:abawo_bt_app/pages/trainer_model_search_page.dart';
import 'package:abawo_bt_app/service/shifter_service.dart';
import 'package:flutter/material.dart';
class TrainerAssignment {
const TrainerAssignment(this.trainer, this.protocol);
final TrainerScanResult trainer;
final String? protocol;
}
class BikeScanDialog extends StatefulWidget {
const BikeScanDialog({
required this.shifter,
@ -12,11 +20,11 @@ class BikeScanDialog extends StatefulWidget {
final ShifterService shifter;
static Future<TrainerScanResult?> show(
static Future<TrainerAssignment?> show(
BuildContext context, {
required ShifterService shifter,
}) {
return showDialog<TrainerScanResult>(
return showDialog<TrainerAssignment>(
context: context,
barrierDismissible: true,
builder: (_) => BikeScanDialog(shifter: shifter),
@ -34,18 +42,88 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
String? _scanError;
final Map<String, TrainerScanResult> _resultsByAddress = {};
StreamSubscription<TrainerScanEvent>? _scanSubscription;
bool _protocolLoading = true;
bool _hasProtocolSelection = false;
String _protocol = 'auto';
String? _modelName;
@override
void initState() {
super.initState();
unawaited(_startScan());
unawaited(_loadProtocol());
}
Future<void> _loadProtocol() async {
final result = await widget.shifter.readTrainerProtocol();
if (!mounted) return;
setState(() {
_protocolLoading = false;
_hasProtocolSelection = result.isOk();
if (result.isOk()) _protocol = result.unwrap();
});
}
Future<void> _chooseModel() async {
// Keep phone navigation separate from the button's scan session.
if (_isScanning) await widget.shifter.stopTrainerScan();
if (!mounted) return;
final model = await Navigator.of(context).push<TrainerModel>(
MaterialPageRoute(
builder: (_) =>
TrainerModelSearchPage(canSelect: _hasProtocolSelection)));
if (!mounted) return;
if (model != null) {
setState(() {
_protocol = model.id;
_modelName = model.name;
_showOnlyFtms = false;
});
}
await _startScan();
}
Future<void> _missingTrainer() async {
final search = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text("I can't find my trainer"),
content: const SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Wake up your trainer and keep it close to your Universal Shifters. Disconnect other training apps, then scan again.'),
SizedBox(height: 12),
Text(
'You may need compatible firmware to connect your trainer with your Universal Shifters.'),
SizedBox(height: 12),
Text(
'Standard firmware supports FTMS trainers and selected Yesoul, Keiser, Tacx, Elite, Wahoo, Echelon, Domyos and elliptical models. Older shipped firmware may support FTMS only.'),
SizedBox(height: 12),
Text(
'For other trainers, search for the exact model to check the required firmware and start a connection.'),
])),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Back')),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Find trainer model')),
],
));
if (search == true && mounted) await _chooseModel();
}
Future<void> _startScan() async {
await _scanSubscription?.cancel();
if (!mounted) return;
if (_isScanning) {
await widget.shifter.stopTrainerScan();
}
if (!mounted) return;
setState(() {
_isStartingScan = true;
@ -70,6 +148,10 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
);
final startResult = await widget.shifter.startTrainerScan();
if (!mounted) {
if (startResult.isOk()) await widget.shifter.stopTrainerScan();
return;
}
if (startResult.isErr()) {
_scanError = startResult.unwrapErr().toString();
} else {
@ -136,17 +218,51 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
height: dialogHeight,
child: Column(
children: [
_DialogHeader(
showOnlyFtms: _showOnlyFtms,
isScanning: _isStartingScan || _isScanning,
onChanged: (value) {
setState(() {
_showOnlyFtms = value;
});
},
onRescan: _startScan,
),
Expanded(child: _buildBody(context)),
Expanded(
child: CustomScrollView(slivers: [
SliverToBoxAdapter(
child: _DialogHeader(
showOnlyFtms: _showOnlyFtms,
isScanning: _isStartingScan || _isScanning,
onChanged: (value) {
setState(() {
_showOnlyFtms = value;
});
},
onRescan: _startScan,
)),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(children: [
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(_protocol == 'auto'
? 'Automatic detection'
: _modelName ?? _protocol),
subtitle: Text(_protocolLoading
? 'Reading trainer selection'
: 'Trainer model'),
trailing: const Icon(Icons.search),
onTap: _protocolLoading ? null : _chooseModel),
if (_protocol != 'auto' && _hasProtocolSelection)
Align(
alignment: Alignment.centerLeft,
child: TextButton(
onPressed: () => setState(() {
_protocol = 'auto';
_modelName = null;
}),
child:
const Text('Use Automatic detection'))),
]))),
_buildBody(context),
])),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: TextButton(
onPressed: _missingTrainer,
child: const Text("I can't find my trainer"))),
],
),
),
@ -155,46 +271,59 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
Widget _buildBody(BuildContext context) {
if (_scanError != null) {
return _ScanMessage(
return SliverToBoxAdapter(
child: _ScanMessage(
message: 'Could not start shifter trainer scan: $_scanError',
action: TextButton.icon(
onPressed: _startScan,
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
),
);
));
}
if (_isStartingScan && _resultsByAddress.isEmpty) {
return const Center(child: CircularProgressIndicator());
return const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator())));
}
final devices = _filteredDevices();
if (devices.isEmpty) {
return _ScanMessage(
return SliverToBoxAdapter(
child: _ScanMessage(
message: _isScanning
? 'The shifter is scanning. Nearby trainers will appear here as soon as the shifter reports them.'
: 'No matching trainers were reported by the shifter. Rescan with the trainer nearby and awake.',
);
));
}
return ListView.separated(
return SliverPadding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
itemCount: devices.length,
separatorBuilder: (_, __) => const SizedBox(height: 12),
itemBuilder: (context, index) => _TrainerScanResultTile(
result: devices[index],
onTap: () => Navigator.of(context).pop(devices[index]),
),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: _TrainerScanResultTile(
result: devices[index],
onTap: () {
if (_protocolLoading) return;
Navigator.of(context).pop(TrainerAssignment(
devices[index],
_hasProtocolSelection ? _protocol : null));
},
)),
childCount: devices.length)),
);
}
List<TrainerScanResult> _filteredDevices() {
final devices = _resultsByAddress.values.where((device) {
return !_showOnlyFtms || device.ftmsDetected;
return !_showOnlyFtms || device.supported;
}).toList(growable: false);
devices.sort((a, b) {
final ftmsCompare = (b.ftmsDetected ? 1 : 0) - (a.ftmsDetected ? 1 : 0);
final ftmsCompare = (b.supported ? 1 : 0) - (a.supported ? 1 : 0);
if (ftmsCompare != 0) {
return ftmsCompare;
}
@ -258,21 +387,24 @@ class _DialogHeader extends StatelessWidget {
],
),
const SizedBox(height: 16),
Row(
Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Expanded(
child: Row(
children: [
Text(
'FTMS only',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 8),
Switch(value: showOnlyFtms, onChanged: onChanged),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
'Supported trainers only',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
)),
const SizedBox(width: 8),
Switch(value: showOnlyFtms, onChanged: onChanged),
],
),
SizedBox(
width: 132,
@ -312,7 +444,11 @@ class _TrainerScanResultTile extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final name = result.name.isEmpty ? 'Unknown Trainer' : result.name;
final typeLabel = result.ftmsDetected ? 'FTMS trainer' : 'Nearby device';
final typeLabel = result.ftmsDetected
? 'FTMS'
: result.supported
? 'Supported'
: 'Nearby device';
final addressText = _formatTrainerAddress(result.address);
return Material(
@ -416,7 +552,8 @@ class _ScanMessage extends StatelessWidget {
return Padding(
padding: const EdgeInsets.all(20),
child: Center(
child: Column(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
@ -428,7 +565,7 @@ class _ScanMessage extends StatelessWidget {
SizedBox(width: 132, child: action!),
],
],
),
)),
),
);
}

View File

@ -0,0 +1,553 @@
import 'dart:async';
import 'package:abawo_bt_app/model/shifter_types.dart';
import 'package:abawo_bt_app/model/simulation.dart';
import 'package:abawo_bt_app/service/shifter_service.dart';
import 'package:flutter/material.dart';
class SimulationCard extends StatefulWidget {
const SimulationCard(
{super.key, required this.shifter, required this.enabled});
final ShifterService shifter;
final bool enabled;
@override
State<SimulationCard> createState() => _SimulationCardState();
}
class _SimulationCardState extends State<SimulationCard> {
final _form = GlobalKey<FormState>();
final _fields = List.generate(5, (_) => TextEditingController());
SimulationConfig _draft = const SimulationConfig();
Map<int, String> _models = {};
SimulationStatus? _status;
StreamSubscription<SimulationStatus>? _subscription;
bool _loading = true;
bool _saving = false;
bool _loaded = false;
bool _dirty = false;
String? _error;
String? _statusError;
int _loadGeneration = 0;
@override
void initState() {
super.initState();
if (widget.enabled) unawaited(_load());
}
@override
void didUpdateWidget(covariant SimulationCard oldWidget) {
super.didUpdateWidget(oldWidget);
if (!widget.enabled && oldWidget.enabled) {
_loadGeneration++;
unawaited(_subscription?.cancel());
_subscription = null;
_status = null;
} else if (widget.enabled && !oldWidget.enabled) {
unawaited(_load());
}
}
@override
void dispose() {
_loadGeneration++;
_subscription?.cancel();
for (final field in _fields) {
field.dispose();
}
super.dispose();
}
void _setDraft(SimulationConfig config) {
_draft = config;
final values = [
config.riderWeight,
config.bikeWeight,
config.gradeMultiplier,
config.rollingMultiplier,
config.windMultiplier
];
for (var i = 0; i < values.length; i++) {
_fields[i].text = values[i].toStringAsFixed(i < 2 ? 2 : 3);
}
}
Future<void> _load() async {
final generation = ++_loadGeneration;
setState(() {
_loading = true;
_error = null;
_statusError = null;
});
await _subscription?.cancel();
_subscription = null;
final config = await widget.shifter.readSimulationConfig();
if (!mounted || generation != _loadGeneration) return;
if (config.isErr()) {
setState(() {
_loading = false;
_loaded = false;
_error =
'Simulation settings could not be read. Older firmware may not support this feature.';
});
return;
}
final catalog =
await widget.shifter.readSetting(simulationModelsCharacteristicUuid);
if (!mounted || generation != _loadGeneration) return;
Map<int, String> models = {};
if (catalog.isOk()) {
try {
models = decodeSimulationModels(catalog.unwrap());
} on FormatException {/* Keep current model. */}
}
final current = config.unwrap();
models.putIfAbsent(current.modelId, () => 'Model ${current.modelId}');
setState(() {
_setDraft(current);
_models = models;
_loading = false;
_loaded = true;
_dirty = false;
});
_subscription =
widget.shifter.subscribeToSimulationStatus().listen((status) {
if (mounted && generation == _loadGeneration) {
setState(() {
_status = status;
_statusError = null;
});
}
}, onError: (Object error) {
if (mounted && generation == _loadGeneration) {
setState(() {
_status = null;
_statusError = 'Live simulation status is unavailable.';
});
}
});
final status =
await widget.shifter.readSetting(simulationStatusCharacteristicUuid);
if (!mounted || generation != _loadGeneration || _status != null) return;
try {
if (status.isErr()) throw const FormatException();
setState(() => _status = SimulationStatus.decode(status.unwrap()));
} on FormatException {
setState(() => _statusError = 'Live simulation status is unavailable.');
}
}
String? _validate(String? raw, int index) {
final value = double.tryParse((raw ?? '').replaceAll(',', '.'));
final min = index == 0 ? 1 : 0;
final max = index == 0
? 300
: index == 1
? 100
: 3;
if (value == null || !value.isFinite || value < min || value > max) {
return 'Enter $min to $max';
}
return null;
}
void _updatePreview() {
setState(() => _dirty = true);
if (List.generate(5, (i) => _validate(_fields[i].text, i))
.any((error) => error != null)) {
return;
}
final values =
_fields.map((f) => double.parse(f.text.replaceAll(',', '.'))).toList();
setState(() => _draft = _draft.copyWith(
riderWeight: values[0],
bikeWeight: values[1],
gradeMultiplier: values[2],
rollingMultiplier: values[3],
windMultiplier: values[4]));
}
Future<void> _save() async {
if (!_form.currentState!.validate() || !widget.enabled) return;
if (List.generate(5, (i) => _validate(_fields[i].text, i))
.any((e) => e != null)) {
setState(() =>
_error = 'Check your weight and advanced settings before saving.');
return;
}
_updatePreview();
setState(() {
_saving = true;
_error = null;
});
final result = await widget.shifter.writeSimulationConfig(_draft);
if (!mounted) return;
setState(() {
_saving = false;
if (result.isErr()) {
_error = result.unwrapErr().toString();
} else {
_dirty = false;
}
});
if (result.isOk()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Simulation settings saved.')));
}
}
Widget _field(int index, String label, String unit) => TextFormField(
controller: _fields[index],
enabled: widget.enabled && !_saving,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(labelText: label, suffixText: unit),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) => _validate(value, index),
onChanged: (_) => _updatePreview(),
);
@override
Widget build(BuildContext context) {
final canEdit = widget.enabled && !_saving;
return Card(
child: Padding(
padding: const EdgeInsets.all(18),
child: Form(
key: _form,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(Icons.landscape_outlined,
color: Theme.of(context).colorScheme.primary),
const SizedBox(width: 10),
Text('Simulation',
style: Theme.of(context).textTheme.titleLarge)
]),
const SizedBox(height: 14),
if (_loading)
const Center(
child: Padding(
padding: EdgeInsets.all(16),
child: CircularProgressIndicator())),
if (_error != null) ...[
Text(_error!,
style: TextStyle(
color: Theme.of(context).colorScheme.error)),
const SizedBox(height: 8),
],
if (!_loaded && !_loading)
TextButton(
onPressed: widget.enabled ? _load : null,
child: const Text('Retry')),
if (_loaded && !_loading) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest
.withValues(alpha: 0.54),
borderRadius: BorderRadius.circular(18)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_status?.label ??
'Waiting for simulation status',
style: const TextStyle(
fontWeight: FontWeight.w600)),
if (_status?.details != null) ...[
const SizedBox(height: 4),
Text(_status!.details!)
],
if (_statusError != null) Text(_statusError!),
])),
const SizedBox(height: 16),
DropdownButtonFormField<SimulationPolicy>(
key: ValueKey(_draft.policy),
initialValue: _draft.policy,
isExpanded: true,
decoration: const InputDecoration(
labelText: 'Simulation mode'),
items: SimulationPolicy.values
.map((p) => DropdownMenuItem(
value: p, child: Text(p.label)))
.toList(),
onChanged: canEdit
? (policy) => setState(() {
_draft = _draft.copyWith(policy: policy);
_dirty = true;
})
: null),
const SizedBox(height: 8),
Text(switch (_draft.policy) {
SimulationPolicy.auto =>
'Use native simulation when available. Otherwise emulate through target power.',
SimulationPolicy.force =>
'Emulate simulation through target power, even when native simulation is available.',
SimulationPolicy.native =>
'Use native simulation only. Do not emulate through target power.',
}),
const SizedBox(height: 6),
const Text(
'Emulation requires target-power control and fresh trainer speed. It cannot add control to a read-only trainer.'),
const SizedBox(height: 18),
LayoutBuilder(builder: (context, constraints) {
if (constraints.maxWidth < 340) {
return Column(children: [
_field(0, 'Rider weight', 'kg'),
const SizedBox(height: 16),
_field(1, 'Bike weight', 'kg')
]);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _field(0, 'Rider weight', 'kg')),
const SizedBox(width: 12),
Expanded(child: _field(1, 'Bike weight', 'kg'))
]);
}),
const SizedBox(height: 10),
const Text(
'ANT+ defaults: 75 kg rider and 10 kg bike. Weight received over ANT+ takes priority until the trainer disconnects. Saved weights are not changed.'),
const SizedBox(height: 8),
ExpansionTile(
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(bottom: 16),
title: const Text('Advanced settings'),
subtitle:
const Text('Model, tuning and power preview'),
children: [
const Text(
'These settings affect local emulation, not native simulation.'),
const SizedBox(height: 16),
DropdownButtonFormField<int>(
key: ValueKey(_draft.modelId),
initialValue: _draft.modelId,
isExpanded: true,
decoration: const InputDecoration(
labelText: 'Simulation model'),
items: _models.entries
.map((entry) => DropdownMenuItem(
value: entry.key,
child: Text(switch (entry.value) {
'fe-c' => 'ANT+ FE-C',
'track-only' => 'Track only',
_ => entry.value
})))
.toList(),
onChanged: canEdit
? (id) => setState(() {
_draft = _draft.copyWith(modelId: id);
_dirty = true;
})
: null),
const SizedBox(height: 16),
_field(2, 'Grade multiplier', 'x'),
const SizedBox(height: 16),
_field(3, 'Rolling resistance multiplier', 'x'),
const SizedBox(height: 16),
_field(4, 'Wind resistance multiplier', 'x'),
const SizedBox(height: 18),
if (_draft.modelId == 1 || _draft.modelId == 2) ...[
const Align(
alignment: Alignment.centerLeft,
child: Text(
"Estimated simulation power with no wind and a gear ratio of 1. Limited by your trainer's power limits.")),
const SizedBox(height: 8),
if (List.generate(
5, (i) => _validate(_fields[i].text, i))
.any((e) => e != null))
const Text(
'Enter valid values to update the preview.'),
PowerPreviewChart(
config: _draft, gradeChart: false),
const SizedBox(height: 20),
PowerPreviewChart(
config: _draft, gradeChart: true),
const SizedBox(height: 8),
const Text(
'Preview uses the weight fields above, default rolling resistance and no drafting. It does not include live ANT+ weight or trainer power limits.'),
] else
const Text(
'Power preview is not available for this model.'),
]),
const SizedBox(height: 12),
Wrap(
spacing: 10,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
FilledButton(
onPressed: canEdit && _dirty ? _save : null,
child: Text(_saving
? 'Saving changes'
: 'Save changes')),
TextButton(
onPressed: canEdit
? () => setState(() {
_setDraft(SimulationConfig(
modelId: _models.containsKey(1)
? 1
: _draft.modelId));
_dirty = true;
})
: null,
child: const Text('Reset to defaults')),
]),
],
]),
)));
}
}
class PowerPreviewChart extends StatefulWidget {
const PowerPreviewChart(
{super.key, required this.config, required this.gradeChart});
final SimulationConfig config;
final bool gradeChart;
@override
State<PowerPreviewChart> createState() => _PowerPreviewChartState();
}
class _PowerPreviewChartState extends State<PowerPreviewChart> {
double _position = 0.5;
@override
Widget build(BuildContext context) {
final grade = widget.gradeChart;
final min = grade ? -5.0 : 0.0;
final max = grade ? 5.0 : 50.0;
final unit = grade ? '%' : 'km/h';
final x = min + (max - min) * _position;
double watts(double x) =>
widget.config.previewWatts(grade ? 15 : x, grade ? x : 0);
final top =
((watts(max) / 50).ceil() * 50).clamp(50, double.infinity).toDouble();
final color = Theme.of(context).colorScheme.primary;
final muted =
Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.65);
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(grade ? 'Power by slope' : 'Power by speed',
style: Theme.of(context).textTheme.titleMedium),
Text(grade ? 'At 15 km/h' : 'At 0% slope',
style: TextStyle(color: muted)),
const SizedBox(height: 12),
Text('${x.toStringAsFixed(1)} $unit: ${watts(x).round()} W',
style: TextStyle(color: color, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
Row(children: [
SizedBox(
width: 48,
height: 150,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${top.round()} W',
style: TextStyle(fontSize: 11, color: muted)),
Text('${(top / 2).round()}',
style: TextStyle(fontSize: 11, color: muted)),
Text('0', style: TextStyle(fontSize: 11, color: muted))
])),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) => GestureDetector(
onTapDown: (event) => setState(() => _position =
(event.localPosition.dx / constraints.maxWidth)
.clamp(0.0, 1.0)),
onHorizontalDragUpdate: (event) => setState(() =>
_position =
(event.localPosition.dx / constraints.maxWidth)
.clamp(0.0, 1.0)),
child: SizedBox(
height: 150,
width: double.infinity,
child: CustomPaint(
painter: _PowerCurvePainter(
values: List.generate(
101,
(i) =>
watts(min + (max - min) * i / 100)),
top: top,
position: _position,
color: color,
grid: Theme.of(context)
.colorScheme
.outlineVariant))),
))),
]),
Padding(
padding: const EdgeInsets.only(left: 48),
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Text('${min.round()} $unit'),
Text('${((min + max) / 2).round()} $unit'),
Text('${max.round()} $unit')
])),
Slider(
value: _position,
onChanged: (value) => setState(() => _position = value),
semanticFormatterCallback: (_) =>
'${x.toStringAsFixed(1)} $unit, ${watts(x).round()} watts'),
]);
}
}
class _PowerCurvePainter extends CustomPainter {
_PowerCurvePainter(
{required this.values,
required this.top,
required this.position,
required this.color,
required this.grid});
final List<double> values;
final double top;
final double position;
final Color color;
final Color grid;
@override
void paint(Canvas canvas, Size size) {
final gridPaint = Paint()
..color = grid.withValues(alpha: 0.5)
..strokeWidth = 1;
for (var i = 0; i <= 4; i++) {
final y = size.height * i / 4;
canvas.drawLine(Offset(0, y), Offset(size.width, y), gridPaint);
}
final path = Path();
for (var i = 0; i < values.length; i++) {
final x = size.width * i / (values.length - 1);
final y = size.height * (1 - values[i] / top);
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
canvas.drawPath(
path,
Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2.5);
final x = position * size.width;
canvas.drawLine(Offset(x, 0), Offset(x, size.height), gridPaint);
final index = position * (values.length - 1);
final lower = index.floor();
final upper = index.ceil();
final value =
values[lower] + (values[upper] - values[lower]) * (index - lower);
canvas.drawCircle(
Offset(x, size.height * (1 - value / top)), 4, Paint()..color = color);
}
@override
bool shouldRepaint(covariant _PowerCurvePainter oldDelegate) => true;
}