url_lancher
通过url_lancher
插件,Flutter可以通过URL跳转浏览器、电话、邮件等三方native应用,url_lancher
同时支持Android和iOS上的使用
https://pub.dev/packages/url_launcher
可以处理的URL种类如下:
类型 | URL | 例子 |
---|---|---|
打开浏览器 | http:<URL> | http://flutter.dev |
拨打电话 | mailto:<address>?subject=<subject>&body=<body> | mailto:foo@example.com?subject=Title&body=Hello! |
发送邮件 | tel:<phone_number> | tel:+12223334444 |
发送SMS | sms:<phone_number> | sms:2223334444 |
Sample
通过一个简单的例子验证一下插件功能:
pubspec.yaml
中添加依赖:
dependencies:
url_launcher: ^5.2.7
实现代码如下:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() => runApp(
MaterialApp(
home: MyApp(),
),
);
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _State();
}
}
class _State extends State<MyApp> {
var _status = 'Ready';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('URL Test'),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RaisedButton(
child: Text('Website'),
onPressed: () {
var url = 'http://flutter.dev';
_launchUrl('$url');
},
),
RaisedButton(
child: Text('Email'),
onPressed: () {
var email = 'test@example.com';
var subject = Uri.encodeComponent('Hello');
var body = Uri.encodeComponent('This is a test.');
var url = 'mailto:$email?subject=$subject&body=$body';
print(url);
_launchUrl(url);
},
),
RaisedButton(
child: Text('Phone'),
onPressed: () {
var tel = '+12345678901';
_launchUrl('tel:$tel');
},
),
RaisedButton(
child: Text('SMS'),
onPressed: () {
var tel = '2345678901';
_launchUrl('sms:$tel');
}),
Text(_status)
],
),
),
);
}
_launchUrl(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
setState(() {
_status = 'Unable to launch url $url';
});
}
}
}
通过launch()
,用对应的应用打开URL。canLaunch()
可以用来检查当前环境是否有可以处理URL的应用,如果没有则返回false