Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Future callback in Flutter

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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(......);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading