flutter打开外部浏览器,打开外部应用,拨打电话发送短信
使用到的是url_launcher 插件 插件地址:https://pub.flutter-io.cn/packages/url_launcher
准备
官方文档给出注意事项,从API30以后,需要在AndroidManifest.xml中加一个<requires> 标签,标签和<application> 同级。 内容如下:
<queries>
<!-- If your app opens https URLs -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
<!-- If your app makes calls -->
<intent>
<action android:name="android.intent.action.DIAL" />
<data android:scheme="tel" />
</intent>
<!-- If your sends SMS messages -->
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="smsto" />
</intent>
<!-- If your app sends emails -->
<intent>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="*/*" />
</intent>
</queries>
使用
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class UrlLauncherPage extends StatefulWidget {
UrlLauncherPage({Key? key}) : super(key: key);
_UrlLauncherPageState createState() => _UrlLauncherPageState();
}
class _UrlLauncherPageState 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: [
ElevatedButton(
child: Text('打开外部浏览器'),
onPressed: () async{
const url = 'https://www.itying.com';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
},
),
SizedBox(height: 10),
ElevatedButton(
child: Text('拨打电话'),
onPressed: () async{
var tel = 'tel:10086';
if (await canLaunch(tel)) {
await launch(tel);
} else {
throw 'Could not launch $tel';
}
},
),
SizedBox(height: 10),
ElevatedButton(
child: Text('发送短信'),
onPressed: () async{
var tel = 'sms:10086';
if (await canLaunch(tel)) {
await launch(tel);
} else {
throw 'Could not launch $tel';
}
},
),
SizedBox(height: 10),
ElevatedButton(
child: Text('打开外部应用'),
onPressed: () async{
var url = 'alipays://';
if (await canLaunch(url)){
await launch(url);
} else {
throw 'Could not launch $url';
}
},
)
]),
)));
}
}
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UrlLauncherPage(),
);
}
}
|