1. 安裝插件
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
date_format: ^1.0.6
flutter_cupertino_date_picker: ^1.0.26+2
flutter_swiper: ^1.1.6
fluttertoast: ^7.1.6
http: ^0.12.2
dio: ^3.0.10
flutter_html: ^1.1.0
flutter_inappwebview: ^4.0.0+4
device_info: ^1.0.0
amap_location: ^0.2.0
image_picker: ^0.6.7+21
video_player: ^1.0.1
chewie: ^0.12.2
connectivity: ^2.0.2
shared_preferences: ^0.5.12+4
barcode_scan_fix: ^1.0.2
package_info: ^0.4.3+2
path_provider: ^1.6.27
open_file: ^3.0.3
flutter_downloader: ^1.5.2
# 打開外部應用
url_launcher: ^5.7.10
在pubspec.yaml中配置保存後,在VS Code環境中會自動下載依賴包。
如果無法正常下載,執行 flutter pub get 。
2. 引入插件
在需要用到的該插件的文件中引入插件包。
import 'package:url_launcher/url_launcher.dart';
3. 使用插件
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class UrlLauncherPage extends StatefulWidget {
UrlLauncherPage({Key key}) : super(key: key);
_UrlLauncherState createState() => _UrlLauncherState();
}
class _UrlLauncherState extends State<UrlLauncherPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('UrlLauncher'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: ListView(
children: [
RaisedButton(
child: Text('打開外部瀏覽器'),
onPressed: () async{
// 蘋果App升級用的此方式
// 前提是首先獲取App在蘋果裏面的地址
const url = 'https://cflutter.com';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
},
),
SizedBox(height: 10),
RaisedButton(
child: Text('撥打電話'),
onPressed: () async{
// 協議格式:tel:<phone number>
var tel = 'tel:10086';
if (await canLaunch(tel)) {
await launch(tel);
} else {
throw 'Could not launch $tel';
}
},
),
SizedBox(height: 10),
RaisedButton(
child: Text('發送短信'),
onPressed: () async{
// 協議格式:sms:<phone number>
var tel = 'sms:10086';
if (await canLaunch(tel)) {
await launch(tel);
} else {
throw 'Could not launch $tel';
}
},
),
SizedBox(height: 10),
RaisedButton(
child: Text('打開外部應用'),
onPressed: () async{
var url = 'alipays://';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
},
) ,
SizedBox(height: 10),
RaisedButton(
child: Text('發送郵件'),
onPressed: () async{
// 協議格式:mailto:<email address>?subject=<subject>&body=<body>
var url = 'mailto:[email protected]?subject=Test&body=測試';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
},
)
]
),
)
)
);
}
}
打開其它應用時,都是改變相應的url協議地址即可,跳轉原理參照原生開發使用的url scheme,常用的如下:
微信: weixin://
京東: openapp.jdmoble://
淘寶: taobao://
Chrome: googlechrome://
百度地圖: baidumap://
高德地圖:androidamap://、iosamap://
效果圖如下:
參考: