我希望我的函数取两个日期,并返回一个Double值,表示从最后日期到剩余日期的进度条。
我的函数只给出第一个值(示例中为56.25%(
示例:开始时间:2022年7月15日结束时间:2022年7月31日现在:2022年7月23日剩余天数:8(16(进度:56.25%2022年7月24日,该功能将返回62.5%等
我的实验代码:(用秒表示清晰(
// ignore_for_file: avoid_print
import 'dart:async';
void main() {
progressDates(DateTime(2022, 7, 15), DateTime(2022, 7, 31));
}
double progressDates(
DateTime date1,
DateTime date2,
) {
DateTime now = DateTime.now();
DateTime nowDay = DateTime(now.year, now.month, now.day);
int dif1 = nowDay
.difference(date1)
.inDays; // The difference between the beginning and the current day
int dif2 = date2
.difference(nowDay)
.inDays; // The difference between the curent and the end
int allDays = date2.difference(date1).inDays;
double inDouble = (dif1 / allDays) * 100;
double temp = 100 / allDays;
DateTime current = DateTime.now();
Stream timer = Stream.periodic(const Duration(seconds: 1), (i) {
current = current.add(const Duration(seconds: 1));
inDouble = inDouble + temp;
return inDouble;
}).take(dif2);
timer.listen((percentage) => percentage);
double result = timer as double;
print(result);
return result;
}
您的函数不是异步的,因此它只会在计算百分比后完成(而无需等待任何Future
(。此时,函数中的所有异步代码都超出了作用域,将不再执行。您可能应该删除方法中与Future
有关的所有内容,然后可能使用Stream.periodic:
const stream = Stream<double>.periodic(Duration(days: 1),
(count) => progressDates(DateTime(2022, 7, 15), DateTime(2022, 7, 31)));
stream.listen((percentage) {
print(percentage);
});