android - 方法没有按照 onPressed 中的书面顺序执行
问题描述
我正在尝试使用一个简单的凸起按钮创建一个颤振应用程序,该按钮执行以下操作:
- 使用 sms 包在后台发送短信 打开网页 2. 在应用程序中(仅 5 秒)使用 url_launcher 打开手机 3. 使用 onPressed 属性进行语音通话的本机应用程序。
我希望它按照这个顺序,这样我就可以在最后打电话了。但是,onPressed 内部首先打开本机电话应用程序,除非我退出电话应用程序,否则我的网页不会打开。
我很难理解为什么首先打开电话本机应用程序,即使我仅在进行 _launchInApp(toLaunch) 调用后才调用 _makePhoneCall() 方法。sendSMS() 被正确调用
如何设置只有在应用程序中打开网页并遵循顺序后才调用电话本机应用程序?任何帮助都会很棒
下面是一段代码:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:sms/sms.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Packages testing',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Packages testing'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _phone = '';
_launchInApp(String url) async {
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
headers: <String, String>{'my_header_key': 'my_header_value'},
);
} else {
throw 'Could not launch $url';
}
}
_makePhoneCall(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
void sendSMS() {
SmsSender sender = new SmsSender();
sender.sendSms(new SmsMessage(_phone, 'Testing Handset'));
}
@override
Widget build(BuildContext context) {
const String toLaunch = 'https://flutter.dev/';
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
onChanged: (String text) => _phone = text,
decoration:
const InputDecoration(hintText: 'Phone Number')),
),
FlatButton(
onPressed: () => setState(() {
sendSMS();
_launchInApp(toLaunch);
_makePhoneCall('tel:$_phone');
}),
child: const Text('Run All'),
),
const Padding(padding: EdgeInsets.all(16.0)),
],
),
],
),
);
}
}
解决方案
您必须在_launchInApp函数之前使用await关键字才能使其正常工作。试试下面的代码。
FlatButton(
onPressed: () aync {
sendSMS();
await _launchInApp(toLaunch);
_makePhoneCall('tel:$_phone');
}),
child: const Text('Run All'),
),
推荐阅读
- azure-devops - 从 Azure DevOps Release Pipeline 获取发布和内部版本号以显示在网站上
- visual-studio-code - wsl的代码路径是什么,因此在用户配置文件中安装了Vscode
- angular - 构造函数完成后注入服务
- python - 用于 .append 函数的循环列表
- regex - 匹配包含 url 的锚标签的正则表达式
- bash - 使用 SED 在文件中由变量指定的行插入一行
- django - 如何从 html 生成 DOC 和 PDF在 Django
- xml - 从 XML 生成带有注释和文档的 XSD
- python - Python Networkx 权重标签定位
- amazon-web-services - 已删除联合登录用户创建的 AWS 资源