Search code examples
androidflutterdartsql-server-2019

How do I run an async function every 10 seconds in Flutter to simulate checking the user's login state?


I have a Flutter app that runs a stored procedure in SQL Server using the sql_conn package. This SP will return the login state of the user. If they are suddenly restricted from being logged in, I want the Flutter app to know about this within 5 seconds.

Below is my code that calls the SP from Flutter. I now need it to run on a 5 second frequency and then handle what happens if the login state is ever 0 (logout and send user back to login screen). How would I do this?

void getLoginState() async {
    await sqlConnect();

    var res = await SqlConn.readData("declare @LoginState bit declare @Status nvarchar(4000) exec spHandheldLogin '${userController.text}', '${passwordController.text}', @LoginState output, @Status output");

    res = json.decode(res); //Gets the first object in the list. This is fine because this SP will only ever return 1 row
    res = res[0];
    var LoginState = res['LoginState'];
    var Status = res['Status'];

    await sqlDisconnect();
}

Solution

  • Try this

    
    import 'dart:async';
    
    Timer? timer;
    
    @override
    void initState() {
      super.initState();
      timer = Timer.periodic(Duration(seconds: 10), (Timer t) => 
      getLoginState()); // Your function
    }
    
    @override
    void dispose() {
      timer?.cancel();
      super.dispose();
    }