首页 > 解决方案 > 如何在颤振中使用 url_launcher 捕获 canLaunch 异常?

问题描述

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

// 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
}

标签: flutterdart

解决方案


我会尝试将 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();

推荐阅读