当我有与此类似的代码时,应用程序将像桌面一样按预期工作。
launchUrl(uri);
setState(() {
paymentLaunched = true;
});
但是,当我有一个包含
launchUrl
函数的异步函数时,移动设备上的客户端应用程序没有任何反应。用户停留在当前网页上。桌面设备在启动 URL 时没有问题,只有移动设备有问题。
getSquareCheckoutLink().then((uri) {
if (uri != null) {
launchUrl(uri);
setState(() {
paymentLaunched = true;
});
}
});
这是
getSquareCheckoutLink()
的实现:
Future<Uri?> getSquareCheckoutLink() async {
final String idemKey = const Uuid().v1();
final SquareAPI api = production;
List<LineItem> lineItemList = [];
BaseMoneyPrice youthPrice = const BaseMoneyPrice(0, "USD");
BaseMoneyPrice adultPrice = const BaseMoneyPrice(2000, "USD");
BaseMoneyPrice seniorPrice = const BaseMoneyPrice(1000, "USD");
if (childTickets > 0) {
lineItemList
.add(LineItem('Youth Ticket', childTickets.toString(), youthPrice));
}
if (adultTickets > 0) {
lineItemList
.add(LineItem("Adult Ticket", adultTickets.toString(), adultPrice));
}
if (seniorTickets > 0) {
lineItemList.add(
LineItem("Senior Ticket", seniorTickets.toString(), seniorPrice));
}
if (lineItemList.isEmpty) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text("Please select tickets to purchase"),
content: Text(
"You do not have any tickets selected to purchase. Please choose ticket(s) for the performance."),
);
});
return null;
}
final data = SquareData(idemKey, OrderData(api.locationId, lineItemList));
http
.post(Uri.parse("/.netlify/functions/square-payments"),
body: data.toJson())
.then((response) {
final jsonResponse = jsonDecode(response.body)["payment_link"];
return Uri.parse(Uri.encodeFull(jsonResponse["url"]));
});
return null;
}
不确定应用程序为什么会这样。我想知道我是否错过了什么。我以前在使用
url_launcher
flutter 包时从未遇到过这个问题。尝试了不同的技术,例如:
如果需要,您可以将此测试数据用于请求。
{"idempotency_key":"512345koo-3479-1hgj-a1c7-8f23ghjk32ac","order":{"location_id":"LQA9TJT2MDK33","line_items":[{"name":"Adult Ticket","quantity":"1","base_price_money":{"amount":2000,"currency":"USD"}}]}}
如果您想在移动设备上测试我的部署,您将看到我提到的行为。
我最终使用文本小部件作为墨水池中的子项来启动 URL 作为解决方法。当 launchUrl 不依赖于另一个进程为其提供 URI 时,它似乎可以工作。
这是我所做的更改:
Center(
child: InkWell(
onTap: () {
launchUrl(link);
setState(() {
msg = "";
});
},
child: Text(
msg,
style: const TextStyle(fontSize: 22, color: Colors.blueAccent),
),
)),
final uri = await getSquareCheckoutLink();
if (uri != null) {
await launchUrl(uri);
setState(() {
link = uri;
msg = "Click here to pay";
paymentLaunched = true;
});
} else {
setState(() {
msg = "Error: Try refreshing page";
});
}
仍然不确定为什么成功获取 URI 后第一次 launchUrl 调用不起作用。然而,只要响应不返回 null 或出现 API 异常,该解决方法似乎就不会失败。
如果有人理解为什么会发生这种情况,请对此进行说明。错误?