gpt4 book ai didi

flutter - 如何在 flutter 中使用 url_launcher 捕获 canLaunch 异常?

转载 作者:IT王子 更新时间:2023-10-29 07:16:46 26 4
gpt4 key购买 nike

使用包中的代码我无法捕捉到异常。请注意,我想捕获这个特定的异常。

// from https://pub.dev/packages/url_launcher
_launchURL() async {
const url = 'myscheme://myurl';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

// my code
try {
_launchURL();
}
catch (e)
{
// although the exception occurs, this never happens, and I would rather catch the exact canLaunch exception
}

最佳答案

我会尝试将 try catch 语句放在函数中。我相信正在发生的事情是 try/catch 语句仅适用于函数调用,尽管它是异步的,但我不相信它实际上会尝试并返回异常。

所以解决方案看起来像这样:

_launchURL() async {
try{

const url = 'myscheme://myurl';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

catch(e){
//debug e
}
}

// my code
launchURL();

关于flutter - 如何在 flutter 中使用 url_launcher 捕获 canLaunch 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57139459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com