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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With