Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Future<bool> in if statement condition?

Tags:

flutter

dart

In Flutter, am using "url_launcher" package which uses Future<bool> to check if the app can launch other apps. Within my code I have phone numbers listed, and I want to place an Icon for WhatsApp only if it is installed on the user's device.

bool hasWhatsApp() {
    var whatsExists;
    canLaunch('https://api.whatsapp.com/').then((val) => whatsExists = val);
    return whatsExists;
  }

am using this function to check inside an if statement to show the icon on the screen or not, however, it keeps returning 'null'.

if (phoneNumber.substring(0, 1) != '2' && hasWhatsApp())
                    IconButton(
                      icon: Image.asset('assets/icons/whatsapp.png'),
                      iconSize: Theme.of(context).iconTheme.size,
                      onPressed: () async {
                          await launch(whatsUrl);
                      },
                    ),

how can I fix this please?

like image 332
Tareq Alothman Avatar asked Mar 10 '26 07:03

Tareq Alothman


1 Answers

What you are trying to do cannot work.

Your function hasWhatsApp is synchronous, so it returns a value immediately when you call it. Inside that function, you start an asynchronous computation, and when that computation finishes (at a later time), it overwrites a local variable. The function has long returned by then.

There is no way you can immediately return a value which is not available until later. It's simply not there.

So, you need to await the future so you can delay making the decision until the value is available. For example, change your if to:

if (phoneNumber.substring(0, 1) != '2' && 
    await canLaunch('https://api.whatsapp.com/')) {
  ...
}

That does mean that you have to make the function containing that if asynchronous. I'm not a Flutter expert, I guess you might need to use a FutureBuilder.

There is no work-around for asynchrony.

like image 188
lrn Avatar answered Mar 11 '26 20:03

lrn