selfprivacy.org.app/lib/ui/components/brand_timer/brand_timer.dart

87 lines
1.9 KiB
Dart
Raw Normal View History

2021-01-06 21:25:53 +02:00
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:selfprivacy/ui/components/brand_text/brand_text.dart';
import 'package:selfprivacy/utils/named_font_weight.dart';
class BrandTimer extends StatefulWidget {
const BrandTimer({
2021-03-15 17:39:44 +02:00
Key? key,
required this.startDateTime,
required this.duration,
2021-01-06 21:25:53 +02:00
}) : super(key: key);
2021-03-15 17:39:44 +02:00
final DateTime? startDateTime;
final Duration? duration;
2021-01-06 21:25:53 +02:00
@override
_BrandTimerState createState() => _BrandTimerState();
}
class _BrandTimerState extends State<BrandTimer> {
2021-03-15 17:39:44 +02:00
String? _timeString;
late Timer timer;
2021-01-06 21:25:53 +02:00
@override
void initState() {
2021-01-19 14:05:40 +02:00
_timerStart();
super.initState();
}
_timerStart() {
2021-01-06 21:25:53 +02:00
_timeString = diffenceFromStart;
timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
2021-03-15 17:39:44 +02:00
var timePassed = DateTime.now().difference(widget.startDateTime!);
if (timePassed > widget.duration!) {
2021-01-06 21:25:53 +02:00
t.cancel();
} else {
_getTime();
}
});
2021-01-19 14:05:40 +02:00
}
@override
void didUpdateWidget(BrandTimer oldWidget) {
if (timer.isActive) {
timer.cancel();
}
_timerStart();
super.didUpdateWidget(oldWidget);
2021-01-06 21:25:53 +02:00
}
@override
Widget build(BuildContext context) {
return BrandText.medium(
_timeString,
style: TextStyle(
fontWeight: NamedFontWeight.demiBold,
),
);
}
void _getTime() {
setState(() {
_timeString = diffenceFromStart;
});
}
String get diffenceFromStart =>
2021-03-15 17:39:44 +02:00
_durationToString(DateTime.now().difference(widget.startDateTime!));
2021-01-06 21:25:53 +02:00
String _durationToString(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
2021-01-21 23:01:42 +02:00
String twoDigitSeconds =
2021-03-15 17:39:44 +02:00
twoDigits(widget.duration!.inSeconds - duration.inSeconds.remainder(60));
2021-01-06 21:25:53 +02:00
2021-01-19 14:05:40 +02:00
return "$twoDigitSeconds cек";
2021-01-06 21:25:53 +02:00
}
@override
void dispose() {
if (timer.isActive) {
timer.cancel();
}
super.dispose();
}
}