如何每天只运行一次代码?

时间:2020-08-23 05:39:36

标签: android ios flutter

我正在使用Flutter。如何每天运行一次功能?我无法使用循环或异步功能每24小时运行一次。有没有办法可以实现?

我想在用户打开应用程序时在启动屏幕中运行它。

3 个答案:

答案 0 :(得分:2)

这将为您工作。从启动中调用此功能

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);
  }
}

答案 1 :(得分:2)

我尝试过,看看是否有效

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")
      }
    
    }

答案 2 :(得分:1)

您可以尝试以下方法:

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'));
}
}