kovinar update code
This commit is contained in:
+635
-334
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// One saved target (a JSON file written by the preview screen).
|
||||
@@ -45,42 +46,74 @@ class Session {
|
||||
|
||||
/// Aggregates over any set of sessions (trainings or tournaments of one format).
|
||||
class ShooterStats {
|
||||
static const int trendWindow = 5;
|
||||
|
||||
final int sessions;
|
||||
final int targets;
|
||||
final int shots;
|
||||
final TargetRecord? best;
|
||||
final Session? bestSession; // highest average per shot
|
||||
final double? averageTarget;
|
||||
final double? averagePerShot;
|
||||
final double? trend; // last sessions minus the ones before them, per shot
|
||||
|
||||
const ShooterStats._({
|
||||
required this.sessions,
|
||||
required this.targets,
|
||||
required this.shots,
|
||||
required this.best,
|
||||
required this.bestSession,
|
||||
required this.averageTarget,
|
||||
required this.averagePerShot,
|
||||
required this.trend,
|
||||
});
|
||||
|
||||
/// [sessions] newest first, as [TargetRepository.loadSessions] returns them.
|
||||
factory ShooterStats.of(List<Session> sessions) {
|
||||
final all = [for (final s in sessions) ...s.targets];
|
||||
final shots = all.fold(0, (sum, t) => sum + t.shots);
|
||||
final total = all.fold(0, (sum, t) => sum + t.score);
|
||||
final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score));
|
||||
final mean = all.isEmpty ? null : total / all.length;
|
||||
|
||||
Session? bestSession;
|
||||
for (final s in sessions) {
|
||||
final avg = s.averagePerShot;
|
||||
if (avg != null &&
|
||||
(bestSession == null || avg > bestSession.averagePerShot!)) {
|
||||
bestSession = s;
|
||||
}
|
||||
}
|
||||
|
||||
return ShooterStats._(
|
||||
sessions: sessions.length,
|
||||
targets: all.length,
|
||||
shots: shots,
|
||||
best: ranked.isEmpty ? null : ranked.first,
|
||||
bestSession: bestSession,
|
||||
averageTarget: mean,
|
||||
averagePerShot: shots == 0 ? null : total / shots,
|
||||
trend: _trend(sessions),
|
||||
);
|
||||
}
|
||||
|
||||
// Average per shot of the newest sessions minus the same number before them
|
||||
static double? _trend(List<Session> newestFirst) {
|
||||
final scored = newestFirst.where((s) => s.shots > 0).toList();
|
||||
final n = min(trendWindow, scored.length ~/ 2);
|
||||
if (n == 0) return null;
|
||||
double avg(Iterable<Session> list) =>
|
||||
list.fold(0, (a, s) => a + s.totalScore) /
|
||||
list.fold(0, (a, s) => a + s.shots);
|
||||
return avg(scored.take(n)) - avg(scored.skip(n).take(n));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and edits the saved targets under <documents>/saved_images/<session>/.
|
||||
///
|
||||
/// Score and shots of every target are cached in <documents>/target_index.json,
|
||||
/// keyed by the file's path with its size and last change, so loading reads one
|
||||
/// file instead of every target. A new, edited or renamed target no longer
|
||||
/// matches its entry and is read again; entries of deleted files are dropped.
|
||||
class TargetRepository {
|
||||
static Map<String, dynamic>? _index; // path in saved_images -> entry
|
||||
|
||||
static Future<Directory> _root() async {
|
||||
final dir = Directory(
|
||||
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
|
||||
@@ -88,15 +121,56 @@ class TargetRepository {
|
||||
return dir;
|
||||
}
|
||||
|
||||
/// Sessions, newest first. With [year], only that year's target files are read.
|
||||
static Future<List<Session>> loadSessions({int? year}) async {
|
||||
static Future<File> _indexFile() async => File(
|
||||
'${(await getApplicationDocumentsDirectory()).path}/target_index.json');
|
||||
|
||||
static Future<Map<String, dynamic>> _loadIndex() async {
|
||||
if (_index != null) return _index!;
|
||||
try {
|
||||
final file = await _indexFile();
|
||||
_index = await file.exists()
|
||||
? jsonDecode(await file.readAsString()) as Map<String, dynamic>
|
||||
: {};
|
||||
} catch (_) {
|
||||
_index = {}; // unreadable: rebuild it from the targets
|
||||
}
|
||||
return _index!;
|
||||
}
|
||||
|
||||
/// Sessions, newest first.
|
||||
static Future<List<Session>> loadSessions() async {
|
||||
final sessions = <Session>[];
|
||||
final index = await _loadIndex();
|
||||
final seen = <String>{};
|
||||
var changed = false;
|
||||
|
||||
for (final folder in await _folders()) {
|
||||
if (year != null && folder.date.year != year) continue;
|
||||
final targets = <TargetRecord>[];
|
||||
for (final file in folder.targetFiles) {
|
||||
final record = await _readTarget(file);
|
||||
final key = '${folder.name}/${file.uri.pathSegments.last}';
|
||||
seen.add(key);
|
||||
final stat = file.statSync();
|
||||
final stamp = '${stat.size}:${stat.modified.millisecondsSinceEpoch}';
|
||||
final cached = index[key];
|
||||
TargetRecord? record;
|
||||
if (cached is Map && cached['stamp'] == stamp) {
|
||||
record = TargetRecord(
|
||||
file: file,
|
||||
shotAt: _timeFromFileName(file) ?? stat.modified,
|
||||
score: cached['score'] as int,
|
||||
shots: cached['shots'] as int,
|
||||
);
|
||||
} else {
|
||||
record = await _readTarget(file);
|
||||
if (record != null) {
|
||||
index[key] = {
|
||||
'stamp': stamp,
|
||||
'score': record.score,
|
||||
'shots': record.shots
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (record != null) targets.add(record);
|
||||
}
|
||||
targets.sort((a, b) => a.shotAt.compareTo(b.shotAt));
|
||||
@@ -108,16 +182,20 @@ class TargetRepository {
|
||||
));
|
||||
}
|
||||
|
||||
final before = index.length;
|
||||
index.removeWhere((key, _) => !seen.contains(key));
|
||||
if (changed || index.length != before) {
|
||||
try {
|
||||
await (await _indexFile()).writeAsString(jsonEncode(index));
|
||||
} catch (_) {
|
||||
// Only a cache: the next load reads the targets again
|
||||
}
|
||||
}
|
||||
|
||||
sessions.sort((a, b) => b.date.compareTo(a.date));
|
||||
return sessions;
|
||||
}
|
||||
|
||||
/// Years that have at least one session, newest first. Reads only metadata.
|
||||
static Future<List<int>> years() async {
|
||||
final years = {for (final f in await _folders()) f.date.year}.toList();
|
||||
return years..sort((a, b) => b.compareTo(a));
|
||||
}
|
||||
|
||||
// Cheap pass over the folders: metadata + file names, no target files read
|
||||
static Future<List<_FolderInfo>> _folders() async {
|
||||
final root = await _root();
|
||||
@@ -128,12 +206,15 @@ class TargetRepository {
|
||||
for (final f in folder.listSync().whereType<File>())
|
||||
if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f,
|
||||
];
|
||||
final fileTimes = files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
|
||||
final fileTimes =
|
||||
files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
|
||||
result.add(_FolderInfo(
|
||||
name: folder.path.split('/').last,
|
||||
isTournament: meta['isTournament'] == true,
|
||||
date: DateTime.tryParse(meta['createdAt'] ?? '') ??
|
||||
(fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed),
|
||||
(fileTimes.isNotEmpty
|
||||
? fileTimes.first
|
||||
: folder.statSync().changed),
|
||||
targetFiles: files,
|
||||
));
|
||||
}
|
||||
@@ -213,5 +294,9 @@ class _FolderInfo {
|
||||
final DateTime date;
|
||||
final List<File> targetFiles;
|
||||
|
||||
const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles});
|
||||
const _FolderInfo(
|
||||
{required this.name,
|
||||
required this.isTournament,
|
||||
required this.date,
|
||||
required this.targetFiles});
|
||||
}
|
||||
|
||||
+69
-12
@@ -1217,18 +1217,6 @@ class AppTranslations {
|
||||
'English': 'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.',
|
||||
'Slovenian': 'Streli 1–5: statistika primerja le tarče z enakim številom strelov. Sive številke še nimajo tarč.',
|
||||
},
|
||||
'Year (top right): choose which year to show.': {
|
||||
'English': 'Year (top right): choose which year to show.',
|
||||
'Slovenian': 'Leto (desno zgoraj): izberi, katero leto se prikaže.',
|
||||
},
|
||||
'Graph: average per shot over time. Tap or drag on it to see each value.': {
|
||||
'English': 'Graph: average per shot over time. Tap or drag on it to see each value.',
|
||||
'Slovenian': 'Graf: povprečje na strel skozi čas. Tapni ali povleci po njem za posamezno vrednost.',
|
||||
},
|
||||
'By date / By score: sort the list by date or by best average per shot.': {
|
||||
'English': 'By date / By score: sort the list by date or by best average per shot.',
|
||||
'Slovenian': 'Po datumu / Po rezultatu: razvrsti seznam po datumu ali po najboljšem povprečju na strel.',
|
||||
},
|
||||
'Tap a session to see all its targets with the selected number of shots on one target.': {
|
||||
'English': 'Tap a session to see all its targets with the selected number of shots on one target.',
|
||||
'Slovenian': 'Tapni sejo za prikaz vseh njenih tarč z izbranim številom strelov na eni tarči.',
|
||||
@@ -1237,6 +1225,75 @@ class AppTranslations {
|
||||
'English': 'Three dots on the right or long press: session details, single targets, rename and delete.',
|
||||
'Slovenian': 'Tri pike na desni ali dolg pritisk: podrobnosti seje, posamezne tarče, preimenovanje in brisanje.',
|
||||
},
|
||||
// Knjiga form sections
|
||||
'Shot average': {
|
||||
'English': 'Shot average',
|
||||
'Slovenian': 'Povprečje strela',
|
||||
},
|
||||
'Number of points': {
|
||||
'English': 'Number of points',
|
||||
'Slovenian': 'Število točk',
|
||||
},
|
||||
'Graph: shot average (left axis) and number of points (right axis). Month shows each session of a month, Year one point per month; the arrows go back through earlier months or years. Tap or drag on it to see the values.': {
|
||||
'English': 'Graph: shot average (left axis) and number of points (right axis). Month shows each session of a month, Year one point per month; the arrows go back through earlier months or years. Tap or drag on it to see the values.',
|
||||
'Slovenian': 'Graf: povprečje strela (leva os) in število točk (desna os). Mesec prikaže vsako sejo meseca, Leto eno točko na mesec; s puščicami greš nazaj po mesecih ali letih. Tapni ali povleci po njem za vrednosti.',
|
||||
},
|
||||
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.': {
|
||||
'English': 'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.',
|
||||
'Slovenian': 'Obdobje (zraven Zgodovine): ta mesec, zadnji 3 meseci, to leto, vse ali svoji datumi. Uporabljata ga zgornja kartica in seznam.',
|
||||
},
|
||||
'Period': {
|
||||
'English': 'Period',
|
||||
'Slovenian': 'Obdobje',
|
||||
},
|
||||
'This month': {
|
||||
'English': 'This month',
|
||||
'Slovenian': 'Ta mesec',
|
||||
},
|
||||
'Last 3 months': {
|
||||
'English': 'Last 3 months',
|
||||
'Slovenian': 'Zadnji 3 meseci',
|
||||
},
|
||||
'This year': {
|
||||
'English': 'This year',
|
||||
'Slovenian': 'To leto',
|
||||
},
|
||||
'Custom range': {
|
||||
'English': 'Custom range',
|
||||
'Slovenian': 'Po meri',
|
||||
},
|
||||
'No sessions in this period': {
|
||||
'English': 'No sessions in this period',
|
||||
'Slovenian': 'V tem obdobju ni sej',
|
||||
},
|
||||
'Month': {
|
||||
'English': 'Month',
|
||||
'Slovenian': 'Mesec',
|
||||
},
|
||||
'Best training / tournament in the top card: tap to open its targets.': {
|
||||
'English': 'Best training / tournament in the top card: tap to open its targets.',
|
||||
'Slovenian': 'Najboljši trening / tekmovanje v zgornji kartici: tapni za prikaz njegovih tarč.',
|
||||
},
|
||||
'vs earlier': {
|
||||
'English': 'vs earlier',
|
||||
'Slovenian': 'glede na prej',
|
||||
},
|
||||
'Best training': {
|
||||
'English': 'Best training',
|
||||
'Slovenian': 'Najboljši trening',
|
||||
},
|
||||
'Best tournament': {
|
||||
'English': 'Best tournament',
|
||||
'Slovenian': 'Najboljše tekmovanje',
|
||||
},
|
||||
'Arrow under the average: your last 5 sessions compared with the 5 before them.': {
|
||||
'English': 'Arrow under the average: your last 5 sessions compared with the 5 before them.',
|
||||
'Slovenian': 'Puščica pod povprečjem: tvojih zadnjih 5 sej v primerjavi s 5 pred njimi.',
|
||||
},
|
||||
'Sort icon: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.': {
|
||||
'English': 'Sort icon: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.',
|
||||
'Slovenian': 'Ikona razvrščanja: tapni za preklop med vrstnim redom po datumu in po najboljšem povprečju na strel. Barvna številka pokaže, koliko seja odstopa od tvojega povprečja.',
|
||||
},
|
||||
'Year': {
|
||||
'English': 'Year',
|
||||
'Slovenian': 'Leto',
|
||||
|
||||
+160
-92
@@ -1,24 +1,36 @@
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChartPoint {
|
||||
final String label; // shown in the tooltip and under the first/last point
|
||||
final double value;
|
||||
enum ChartAxis { left, right, none }
|
||||
|
||||
const ChartPoint(this.label, this.value);
|
||||
/// One line on the chart. Each series has its own scale, so values of very
|
||||
/// different size (average per shot vs. session total) can share the chart.
|
||||
/// [axis] says which side labels its scale.
|
||||
class ChartSeries {
|
||||
final String name;
|
||||
final Color color;
|
||||
final List<double> values; // one per label
|
||||
final int decimals;
|
||||
final ChartAxis axis;
|
||||
|
||||
const ChartSeries(this.name, this.color, this.values,
|
||||
{this.decimals = 2, this.axis = ChartAxis.none});
|
||||
|
||||
String format(double v) => v.toStringAsFixed(decimals);
|
||||
}
|
||||
|
||||
/// Single-series line chart: 2px line, 8px points, three faint gridlines.
|
||||
/// Tap (or drag) to show the nearest point's label and value.
|
||||
/// Line chart: 2px lines, 8px points, three faint gridlines, up to one labelled
|
||||
/// axis per side. Tap (or drag) to show every series' value at the nearest point.
|
||||
class ProgressChart extends StatefulWidget {
|
||||
final List<ChartPoint> points;
|
||||
final Color color;
|
||||
final List<String> labels; // shown in the tooltip and under the first/last point
|
||||
final List<ChartSeries> series; // legend and tooltip order
|
||||
final Color textColor;
|
||||
final Color gridColor;
|
||||
|
||||
const ProgressChart({
|
||||
super.key,
|
||||
required this.points,
|
||||
required this.color,
|
||||
required this.labels,
|
||||
required this.series,
|
||||
required this.textColor,
|
||||
required this.gridColor,
|
||||
});
|
||||
@@ -31,120 +43,180 @@ class _ProgressChartState extends State<ProgressChart> {
|
||||
int? _selected;
|
||||
|
||||
void _select(Offset position, Size size) {
|
||||
final n = widget.points.length;
|
||||
final n = widget.labels.length;
|
||||
if (n == 0) return;
|
||||
final plotWidth = size.width - _ChartPainter.leftAxis - _ChartPainter.pad * 2;
|
||||
final x = (position.dx - _ChartPainter.leftAxis - _ChartPainter.pad) / plotWidth;
|
||||
final plot = _ChartPainter.plotRect(size);
|
||||
final x = (position.dx - plot.left) / plot.width;
|
||||
setState(() => _selected = (x * (n - 1)).round().clamp(0, n - 1));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final size = Size(constraints.maxWidth, 170);
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTapDown: (d) => _select(d.localPosition, size),
|
||||
onHorizontalDragUpdate: (d) => _select(d.localPosition, size),
|
||||
child: CustomPaint(
|
||||
size: size,
|
||||
painter: _ChartPainter(
|
||||
points: widget.points,
|
||||
color: widget.color,
|
||||
textColor: widget.textColor,
|
||||
gridColor: widget.gridColor,
|
||||
selected: _selected,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final size = Size(constraints.maxWidth, 190);
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTapDown: (d) => _select(d.localPosition, size),
|
||||
onHorizontalDragUpdate: (d) => _select(d.localPosition, size),
|
||||
child: CustomPaint(
|
||||
size: size,
|
||||
painter: _ChartPainter(
|
||||
labels: widget.labels,
|
||||
series: widget.series,
|
||||
textColor: widget.textColor,
|
||||
gridColor: widget.gridColor,
|
||||
selected: _selected,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// Legend, centred under the graph
|
||||
Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final s in widget.series)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 14,
|
||||
height: 3,
|
||||
decoration: BoxDecoration(color: s.color, borderRadius: BorderRadius.circular(2)),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(s.name, style: TextStyle(fontSize: 12, color: widget.textColor)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChartPainter extends CustomPainter {
|
||||
static const double leftAxis = 32; // room for y labels
|
||||
static const double axis = 34; // room for y labels on each side
|
||||
static const double pad = 10; // keeps end points inside the plot
|
||||
static const double top = 34; // room for the tooltip
|
||||
static const double bottom = 20; // room for x labels
|
||||
|
||||
final List<ChartPoint> points;
|
||||
final Color color;
|
||||
static Rect plotRect(Size size) =>
|
||||
Rect.fromLTRB(axis + pad, top, size.width - axis - pad, size.height - bottom);
|
||||
|
||||
final List<String> labels;
|
||||
final List<ChartSeries> series;
|
||||
final Color textColor;
|
||||
final Color gridColor;
|
||||
final int? selected;
|
||||
|
||||
_ChartPainter({
|
||||
required this.points,
|
||||
required this.color,
|
||||
required this.labels,
|
||||
required this.series,
|
||||
required this.textColor,
|
||||
required this.gridColor,
|
||||
required this.selected,
|
||||
});
|
||||
|
||||
// Min and max of a series, widened so a flat line sits in the middle
|
||||
static (double, double) _range(List<double> values, double minSpan) {
|
||||
var lo = values.reduce(min);
|
||||
var hi = values.reduce(max);
|
||||
if (hi - lo < minSpan) {
|
||||
final mid = (hi + lo) / 2;
|
||||
lo = mid - minSpan / 2;
|
||||
hi = mid + minSpan / 2;
|
||||
}
|
||||
return (lo, hi);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
if (points.isEmpty) return;
|
||||
final values = points.map((p) => p.value);
|
||||
var minV = values.reduce((a, b) => a < b ? a : b);
|
||||
var maxV = values.reduce((a, b) => a > b ? a : b);
|
||||
if (maxV - minV < 1) {
|
||||
minV -= 0.5;
|
||||
maxV += 0.5;
|
||||
}
|
||||
final plot = Rect.fromLTRB(leftAxis + pad, top, size.width - pad, size.height - bottom);
|
||||
if (labels.isEmpty || series.isEmpty) return;
|
||||
final plot = plotRect(size);
|
||||
final n = labels.length;
|
||||
final ranges = [
|
||||
for (final s in series) _range(s.values, s.values.reduce(max).abs() * 0.1 + 0.2),
|
||||
];
|
||||
|
||||
Offset at(int i) => Offset(
|
||||
points.length == 1 ? plot.center.dx : plot.left + plot.width * i / (points.length - 1),
|
||||
plot.bottom - plot.height * (points[i].value - minV) / (maxV - minV),
|
||||
);
|
||||
double xAt(int i) => n == 1 ? plot.center.dx : plot.left + plot.width * i / (n - 1);
|
||||
double yAt(double v, (double, double) r) => plot.bottom - plot.height * (v - r.$1) / (r.$2 - r.$1);
|
||||
|
||||
// Gridlines + y labels (min, mid, max)
|
||||
// Gridlines + y labels in each axis series' colour
|
||||
final grid = Paint()
|
||||
..color = gridColor
|
||||
..strokeWidth = 1;
|
||||
for (final f in [0.0, 0.5, 1.0]) {
|
||||
final y = plot.bottom - plot.height * f;
|
||||
canvas.drawLine(Offset(leftAxis, y), Offset(size.width, y), grid);
|
||||
_text(canvas, (minV + (maxV - minV) * f).toStringAsFixed(1), Offset(0, y - 7), 11, textColor);
|
||||
canvas.drawLine(Offset(axis, y), Offset(size.width - axis, y), grid);
|
||||
for (int k = 0; k < series.length; k++) {
|
||||
if (series[k].axis == ChartAxis.none) continue;
|
||||
final right = series[k].axis == ChartAxis.right;
|
||||
final r = ranges[k];
|
||||
final v = r.$1 + (r.$2 - r.$1) * f;
|
||||
final text = series[k].decimals == 0 ? v.round().toString() : v.toStringAsFixed(1);
|
||||
_text(canvas, text, Offset(right ? size.width : 0, y - 7), 11, series[k].color, alignRight: right);
|
||||
}
|
||||
}
|
||||
|
||||
// x labels: first and last only
|
||||
_text(canvas, points.first.label, Offset(plot.left - pad, plot.bottom + 5), 11, textColor);
|
||||
if (points.length > 1) {
|
||||
_text(canvas, points.last.label, Offset(plot.right, plot.bottom + 5), 11, textColor, alignRight: true);
|
||||
_text(canvas, labels.first, Offset(plot.left - pad, plot.bottom + 5), 11, textColor);
|
||||
if (n > 1) {
|
||||
_text(canvas, labels.last, Offset(plot.right + pad, plot.bottom + 5), 11, textColor, alignRight: true);
|
||||
}
|
||||
|
||||
// Line
|
||||
final path = Path()..moveTo(at(0).dx, at(0).dy);
|
||||
for (int i = 1; i < points.length; i++) {
|
||||
path.lineTo(at(i).dx, at(i).dy);
|
||||
}
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = color
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeJoin = StrokeJoin.round,
|
||||
);
|
||||
|
||||
// Points with a surface ring so they read on top of the line
|
||||
for (int i = 0; i < points.length; i++) {
|
||||
final isSel = i == selected;
|
||||
canvas.drawCircle(at(i), isSel ? 7 : 5, Paint()..color = Colors.white);
|
||||
canvas.drawCircle(at(i), isSel ? 5.5 : 4, Paint()..color = color);
|
||||
// Lines, last series first so the main one stays on top
|
||||
for (int k = series.length - 1; k >= 0; k--) {
|
||||
final s = series[k];
|
||||
final r = ranges[k];
|
||||
final path = Path()..moveTo(xAt(0), yAt(s.values[0], r));
|
||||
for (int i = 1; i < n; i++) {
|
||||
path.lineTo(xAt(i), yAt(s.values[i], r));
|
||||
}
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = s.color
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeJoin = StrokeJoin.round,
|
||||
);
|
||||
// Points with a surface ring so they read on top of the line
|
||||
for (int i = 0; i < n; i++) {
|
||||
final isSel = i == selected;
|
||||
final p = Offset(xAt(i), yAt(s.values[i], r));
|
||||
canvas.drawCircle(p, isSel ? 6 : 4.5, Paint()..color = Colors.white);
|
||||
canvas.drawCircle(p, isSel ? 4.5 : 3.5, Paint()..color = s.color);
|
||||
}
|
||||
}
|
||||
|
||||
// Tooltip for the selected point
|
||||
// Tooltip for the selected point: label, then each value in its colour
|
||||
if (selected != null) {
|
||||
final p = at(selected!);
|
||||
canvas.drawLine(Offset(p.dx, plot.top), Offset(p.dx, plot.bottom), grid);
|
||||
final label = '${points[selected!].label} ${points[selected!].value.toStringAsFixed(2)}';
|
||||
final tp = _layout(label, 12, Colors.white, bold: true);
|
||||
final i = selected!;
|
||||
canvas.drawLine(Offset(xAt(i), plot.top), Offset(xAt(i), plot.bottom), grid);
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white),
|
||||
children: [
|
||||
TextSpan(text: labels[i]),
|
||||
for (final s in series)
|
||||
TextSpan(
|
||||
text: ' ${s.format(s.values[i])}',
|
||||
style: TextStyle(color: Color.lerp(s.color, Colors.white, 0.35)),
|
||||
),
|
||||
],
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout(maxWidth: size.width - 16);
|
||||
final w = tp.width + 16;
|
||||
final left = (p.dx - w / 2).clamp(0.0, size.width - w);
|
||||
final left = (xAt(i) - w / 2).clamp(0.0, size.width - w);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(Rect.fromLTWH(left, 2, w, 24), const Radius.circular(6)),
|
||||
Paint()..color = Colors.grey[900]!,
|
||||
@@ -153,22 +225,18 @@ class _ChartPainter extends CustomPainter {
|
||||
}
|
||||
}
|
||||
|
||||
TextPainter _layout(String text, double size, Color color, {bool bold = false}) {
|
||||
return TextPainter(
|
||||
text: TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(fontSize: size, color: color, fontWeight: bold ? FontWeight.w600 : FontWeight.normal),
|
||||
),
|
||||
void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) {
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(text: text, style: TextStyle(fontSize: size, color: color)),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
}
|
||||
|
||||
void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) {
|
||||
final tp = _layout(text, size, color);
|
||||
tp.paint(canvas, alignRight ? at.translate(-tp.width, 0) : at);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_ChartPainter old) =>
|
||||
old.points != points || old.selected != selected || old.color != color || old.textColor != textColor;
|
||||
old.labels != labels ||
|
||||
old.series != series ||
|
||||
old.selected != selected ||
|
||||
old.textColor != textColor;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user