【发布时间】:2020-08-23 05:39:36
【问题描述】:
我正在使用 Flutter。如何每天运行一次函数?我不能使用循环或异步函数每 24 小时运行一次。有什么办法可以实现吗?
我想在用户打开应用时在启动画面中运行它。
【问题讨论】:
-
你想在后台运行这个函数还是在应用打开的时候运行这个函数?
-
我想在启动画面中运行它。 @DeepakRor
我正在使用 Flutter。如何每天运行一次函数?我不能使用循环或异步函数每 24 小时运行一次。有什么办法可以实现吗?
我想在用户打开应用时在启动画面中运行它。
【问题讨论】:
我试过了,看看有没有用
void main() async {
//checking current date
final currentdate = new DateTime.now().day;
//you need to import this Shared preferences plugin
SharedPreferences prefs = await SharedPreferences.getInstance();
//getting last date
int lastDay = (prefs.getInt('day') ?? 0);
//check is code already display or not
if(currentdate!=lastDay){
await prefs.setInt('day', currentdate);
//your code will run once in day
print("hello will display once")
}
}
【讨论】:
这对你有用。从splash调用这个函数
checkIsTodayVisit() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
SharedPreferences preferences = await _prefs;
String lastVisitDate = preferences.get("mDateKey");
String toDayDate = DateTime.now().day.toString(); // Here is you just get only date not Time.
if (toDayDate == lastVisitDate) {
// this is the user same day visit again and again
} else {
// this is the user first time visit
preferences.setString("mDateKey", toDayDate);
}
}
【讨论】:
你可以试试这个:
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(Duration(seconds: 3), handleScreenChange);
}
handleScreenChange() {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen(),
));
}
@override
Widget build(BuildContext context) {
// You can chnage splash screen view like you want
return Container(child: Text('SplashScreen'));
}
}
【讨论】: