【问题标题】:How to run a piece of code only once everyday? [closed]如何每天只运行一次代码? [关闭]
【发布时间】:2020-08-23 05:39:36
【问题描述】:

我正在使用 Flutter。如何每天运行一次函数?我不能使用循环或异步函数每 24 小时运行一次。有什么办法可以实现吗?

我想在用户打开应用时在启动画面中运行它。

【问题讨论】:

  • 你想在后台运行这个函数还是在应用打开的时候运行这个函数?
  • 我想在启动画面中运行它。 @DeepakRor

标签: android ios flutter


【解决方案1】:

我试过了,看看有没有用

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】:

    这对你有用。从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);
      }
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试这个:

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

      【讨论】:

      • 这与问题有什么关系?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多