Home > other >  is it possible to use await in a sync function in dart
is it possible to use await in a sync function in dart

Time:10-30

I have a function to get the user login status, now I want to add a logic with silent login when checked user did not login.After the user log, I store the login information about user name and password into local secure storage after the user login for the first time, when invoke the islogin function, my code looks like this:

bool get isLogin {
    if(this == null){
      // not login, do the automatic login logic
      final UserAccount userAccount = UserAccount();
      final String? phone = await SecureStorageUtil.getString("username");
      final String? password = await SecureStorageUtil.getString("password");
      if(phone == null || password == null){
        return false;
      }
      final Result<Map> result = await userAccount.login(phone, password);
      if(result != null){
        return true;
      }
    }
    return this != null;
  }

what make me stuck is that the fetch credential information and login was async and have to using await keywords to wait the return. But the await keyword only allow in async function.

The await expression can only be used in an async function.

If I change the isLogin function to async, many places in this project must change. I was wonder is it possible to using await in the sync function? so I could do the auto login if the user logined for only one time. And did not do any change with the previous code.

CodePudding user response:

Try to replace you function signature with

Future<bool> get isLogin async {

CodePudding user response:

Timer timer;

@override
void initState() {
  super.initState();
  timer = new Timer.periodic(new Duration(seconds: 1), (Timer timer) async {
      await this.getUserVerificationInfo();
  });
}

@override
void dispose() {
    super.dispose();
    timer.cancel();
}

getUserVerificationInfo() async {
   await someAsyncFunc();
   timer.cancle();
}
  • Related