Home > database >  How can I run IF conditions after getting the data from the database and not before?
How can I run IF conditions after getting the data from the database and not before?

Time:10-29

I have this funtion which gets data from a database.

Future reg() async {
    try {
        getData().then((value) async {
            Dio dio = Dio();
            Response response = await dio.get(
            'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
            return response;
        });
    } catch (e) {}
}

Now I request the data and check for some conditions but, the if conditions are ran first before getting the data from the database and the data arrives after the complete execution of code (Which I know because it can print the correct data after checking the IF conditions).

else {
    var response = await reg();
    if (response != null) {
        if (response.data == "done") {
            showErrorDialog(context, "Done",
            "Your Account has been Created, please Log in");
        } else if (response.data == "key") {
            showErrorDialog(
            context,
            "Incorrect API Key/Main Server Password",
            "The API Key (Main Server Password) is Incorrect. Kindly, Ensure the Key.");
        } else if (response.data == "email") {
            showErrorDialog(context, "Account Already Exists",
            "An Account already exists with this Email");
        } else if (response.data == "username") {
            showErrorDialog(context, "Account Already Exists",
            "An Account already exists with this Username");
        }
    }
}

How can I run these IF conditions after getting the data from the database?

CodePudding user response:

You're missing a return in your reg() function. Add one before your getData() call like this:

Future reg() async {
    try {
        return getData().then((value) async {
            Dio dio = Dio();
            Response response = await dio.get(
            'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
            return response;
        });
    } catch (e) {}
}

Now the function should be properly awaited because it is now returning a promise instead of nothing.

Alternatively, you might prefer to rewrite it using more async/await for easier comprehension, like this:

Future reg() async {
    try {
        const value = await getData();
        Dio dio = Dio();
        Response response = await dio.get(
        'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
        return response;
    } catch (e) {}
}
  • Related