Home > front end >  How to get Future callback in Flutter
How to get Future callback in Flutter

Time:10-20

Good day. I am a flutter beginner and now do some simple pratice.

I want: Press a button and call login api, if api response is success then go to main page.

but I don't know how to get callback result.

viewModel

  Future<String> login(String account, String password) async {
    try {
      futureLogin = logon(account, password);
        await futureLogin.then((value) {

          print("key=${value.data.key}");//success print correct key

          return value.data.key;

        }).catchError((error) {
          print("error=$error");
        });
    } catch (error) {}

    return "";
  }

Button click event

onPressed: () async {
    var result = await viewModel.login(account, password);
    print("result=${result}");//print ""
}

I think that I can simply use await keyword to get my api result but not works.

How to solve it.

Any help will be appreciate.

CodePudding user response:

Try using async await :

Future<String> login(String account, String password) async {
    try {
      futureLogin = logon(account, password);
      var value = await futureLogin;
      return value.data.key;
    } catch (error) {
        return "";
    }
  }

or using .then function add return key after calling futureLogin

return await futureLogin.then(......);

CodePudding user response:

The problem is that you in return is not from the login function but from then function and this result nobody use. After this you make return with empty string Change your code to

   Future<String> login(String account, String password) async {
       try {
           final result = await logon(account, password);
           print("key=${result.data.key}");//success print correct key
           return data.key;
       } catch (error) {
           print("error=$error");
       }

       return "";
   }
  • Related