| 1 | import 'package:flutter/material.dart'; |
| 2 | import 'dart:async'; |
| 3 | import 'package:cake_wallet/generated/i18n.dart'; |
| 4 | |
| 5 | class TimerWidget extends StatefulWidget { |
| 6 | TimerWidget(this.expiratedAt, {this.color = Colors.black}); |
| 7 | |
| 8 | final DateTime expiratedAt; |
| 9 | final Color color; |
| 10 | |
| 11 | @override |
| 12 | TimerWidgetState createState() => TimerWidgetState(); |
| 13 | } |
| 14 | |
| 15 | class TimerWidgetState extends State<TimerWidget> { |
| 16 | TimerWidgetState() |
| 17 | : _leftSeconds = 0, |
| 18 | _minutes = 0, |
| 19 | _seconds = 0, |
| 20 | _isExpired = false; |
| 21 | |
| 22 | int _leftSeconds; |
| 23 | int _minutes; |
| 24 | int _seconds; |
| 25 | bool _isExpired; |
| 26 | Timer? _timer; |
| 27 | |
| 28 | @override |
| 29 | void initState() { |
| 30 | super.initState(); |
| 31 | final start = DateTime.now(); |
| 32 | _isExpired = false; |
| 33 | _leftSeconds = widget.expiratedAt.difference(start).inSeconds; |
| 34 | _recalculate(); |
| 35 | |
| 36 | WidgetsBinding.instance.addPostFrameCallback((_) { |
| 37 | _timer = Timer.periodic(Duration(seconds: 1), (timer) { |
| 38 | if (_isExpired) { |
| 39 | timer.cancel(); |
| 40 | } |
| 41 | |
| 42 | _leftSeconds--; |
| 43 | _isExpired = _leftSeconds <= 0; |
| 44 | _recalculate(); |
| 45 | setState(() {}); |
| 46 | }); |
| 47 | }); |
| 48 | } |
| 49 | |
| 50 | @override |
| 51 | void dispose() { |
| 52 | _timer?.cancel(); |
| 53 | super.dispose(); |
| 54 | } |
| 55 | |
| 56 | @override |
| 57 | Widget build(BuildContext context) { |
| 58 | return _isExpired |
| 59 | ? Text( |
| 60 | S.of(context).expired, |
| 61 | style: Theme.of(context).textTheme.bodyMedium!.copyWith( |
| 62 | fontWeight: FontWeight.w500, |
| 63 | color: Theme.of(context).colorScheme.errorContainer, |
| 64 | ), |
| 65 | ) |
| 66 | : Text( |
| 67 | S.of(context).time(_minutes.toString(), _seconds.toString()), |
| 68 | style: Theme.of(context).textTheme.bodyMedium?.copyWith( |
| 69 | fontWeight: FontWeight.w500, |
| 70 | color: widget.color, |
| 71 | ), |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | void _recalculate() { |
| 76 | _minutes = _leftSeconds ~/ 60; |
| 77 | _seconds = _leftSeconds % 60; |
| 78 | } |
| 79 | } |