date countdown in dart

后端 未结 1 1292
滥情空心
滥情空心 2021-01-22 07:12

am trying to create a countdown on specific date i have and display how many hours, minutes and seconds left until then ..

for example i want to set the counter date to:

相关标签:
1条回答
  • 2021-01-22 07:27

    First of all - there is error: you have to use data.remaining.inMilliseconds instead of data.remaining.inSeconds

    For formatting it'll be better to use Duration instead of DateTime. But you can change your existing code like:

    var format = new DateFormat("mm:ss");
    var dateString = '${data.remaining.inHours}:${format.format(DateTime.fromMillisecondsSinceEpoch(data.remaining.inMilliseconds))};
    print(dateString);
    

    UPD Widget for showing remaining time

    int estimateTs = DateTime(2018, 11, 5, 7, 15, 30).millisecondsSinceEpoch; // set needed date
    
    ....
    
    StreamBuilder(
                          stream: Stream.periodic(Duration(seconds: 1), (i) => i),
                          builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                            DateFormat format = DateFormat("mm:ss");
                            int now = DateTime
                                .now()
                                .millisecondsSinceEpoch;
                            Duration remaining = Duration(milliseconds: estimateTs - now);
                            var dateString = '${remaining.inHours}:${format.format(
                                DateTime.fromMillisecondsSinceEpoch(remaining.inMilliseconds))}';
                            print(dateString);
                            return Container(color: Colors.greenAccent.withOpacity(0.3),
                              alignment: Alignment.center,
                              child: Text(dateString),);
                          });
    
    0 讨论(0)
提交回复
热议问题