需求:打开指定网页、指定应用
这里用到的是一个三方插件 url_launcher 5.0.2版本,
pubspec.ymal文件下dependencies节点增加,例如:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
url_launcher: ^5.0.2
接下来先实现一个点击事件 例如: GestureDetector 的onTap,点击后启动一个打开网页操作,url_launcher 里面有一个 launcher(url) 的 API.
这里我们打开慕课网作为例子,”https://coding.imooc.com/lesson/321.html#mid=24170“,
重点说一下,使用异步方式来实现,启动前要先判断地址是否有效, 具体代码如下:
launcherUrl() async {
var url = "https://coding.imooc.com/lesson/321.html#mid=24170";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'cloud not launcher url';
}
}
运行,成功打开网页。
同样的打开应用也是同理,不过我们要多几个步骤,