~cytrogen/fluent-reader-mobile

ref: c0d14efdf8d5aaceda14c2382bc3d5861ae2b895 fluent-reader-mobile/lib/components/time_text.dart -rw-r--r-- 1.7 KiB
c0d14efd — 刘浩远 add app store link 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import 'dart:async';

import 'package:flutter/cupertino.dart';

class TimeText extends StatefulWidget {
  final DateTime date;
  final TextStyle style;

  TimeText(this.date, {this.style, Key key}) : super(key: key);

  @override
  _TimeTextState createState() => _TimeTextState();
}

class _TimeTextState extends State<TimeText> {
  Timer _timer;
  Duration _duration;

  int diffMinutes() {
    final now = DateTime.now();
    return now.difference(widget.date).inMinutes;
  }

  @override
  void initState() {
    super.initState();
    updateTimer();
  }

  void updateTimer() {
    final diff = diffMinutes();
    Duration duration;
    if (diff < 60) {
      duration = Duration(minutes: 1);
    } else if (diff < 60 * 24) {
      duration = Duration(minutes: 60 - diff % 60);
    } else {
      duration = Duration(minutes: (60 * 24) - diff % (60 * 24));
    }
    if (_duration == null || duration.compareTo(_duration) != 0) {
      _duration = duration;
      if (_timer != null) _timer.cancel();
      _timer = Timer.periodic(duration, (_) {
        setState(() {});
        updateTimer();
      });
    }
  }

  @override
  void dispose() {
    if (_timer != null) _timer.cancel();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant TimeText oldWidget) {
    if (oldWidget.date.compareTo(widget.date) != 0) updateTimer();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    final diff = diffMinutes();
    String label;
    if (diff < 60) {
      label = "${diff}m";
    } else if (diff < 60 * 24) {
      label = "${diff ~/ 60}h";
    } else {
      label = "${diff ~/ (60 * 24)}d";
    }
    return Text(label, style: widget.style);
  }
}