url_launcher导入错误:目标URI不存在
我正在把 url_launcher 集成到我基于Flutter的支付SDK中:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
class _PGPaymentModalState extends State<ArtoPaymentModal> {
late final WebViewController _controller;
bool _isLoading = true;
@override
void initState() {
super.initState();
WebViewCookieManager().clearCookies();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(Colors.white)
..addJavaScriptChannel(
'PGSdkChannel',
onMessageReceived: (JavaScriptMessage message) {
_handleMessage(message.message);
},
)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) async {
final theUrl = request.url;
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
debugPrint('Cannot open URL: $url');
}
return NavigationDecision.prevent; // Cegah WebView load
},
),
)
..loadRequest(Uri.parse(url));
}
VSCode提供了这个错误:
Target of URI doesn't exist: 'package:url_launcher/url_launcher.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.darturi_does_not_exist
我已经在pubspec.yaml中添加了url_launcher,并重新运行 flutter pub get:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
webview_flutter: ^4.13.1
url_launcher: ^6.3.2
删除 pubspec.lock 和 .dart_tool 目录后再运行 flutter pub get 仍然无法解决问题。该如何修复?我正在使用Flutter 3.41.9
解决方案
在上面的代码中你使用了:
final theUrl = request.url;
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
debugPrint('Cannot open URL: $url');
}
但变量 "uri" 不存在。应该改为:
final theUrl = request.url;
final uri = Uri.parse(theUrl) // This might change depending upon the type of response
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
debugPrint('Cannot open URL: $url');
}
此外你还应该运行以下这些命令:
flutter pub add url_launcher
flutter clean
flutter pub get
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。