我正在创建该网站的 WebView https://nearxt.com/ 它在打开时询问位置,但是当我使用此链接在 flutter 中创建 webview 时 那么它就无法定位 我还在应用程序中定义了位置,但 webview 无法接收位置
SafeArea(
child: WebView(
javascriptMode: JavascriptMode.unrestricted,
initialUrl: flutterUrl,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
),
),
flutter 中不支持此功能。即使您尝试使用权限处理程序请求位置访问,应用程序也会拒绝它,并且如果您从手机手动向应用程序授予位置权限,它仍然无法捕获实时位置。建议使用普通的旧java,你可以在互联网上找到很多关于java中的webview的帮助,并且具有位置访问功能,它工作得非常完美。
使用 flutter_inappwebview 获取用户位置
InAppWebView(
initialUrlRequest:
URLRequest(url: Uri.parse('your link here')),
androidOnGeolocationPermissionsShowPrompt:
(InAppWebViewController controller, String origin) async {
return GeolocationPermissionShowPromptResponse(
origin: origin,
allow: true,
retain: true
);
},
)
现在可以使用 webview_flutter:
首先,您需要将 permission_handler、webview_flutter 和 webview_flutter_android 添加到您的
pubspec.yaml
并运行 flutter pub get
dependencies:
permission_handler: ^11.3.0
webview_flutter: ^4.7.0
webview_flutter_android: ^3.15.0
permission_handler
需要针对 iOS 和 Android 进行额外设置,请参阅 readme 了解更多信息。
然后,当网站尝试使用 Geolocation API 时,您可以使用
setGeolocationPermissionsPromptCallbacks
向用户请求位置权限:
final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest('your_url');
final platformController = controller.platform;
if (platformController is AndroidWebViewController) {
platformController.setGeolocationPermissionsPromptCallbacks(
onShowPrompt: (request) async {
// request location permission
final locationPermissionStatus = await Permission.locationWhenInUse.request();
// return the response
return GeolocationPermissionsResponse(
allow: locationPermissionStatus == PermissionStatus.granted,
retain: false,
);
},
);
}
这是一个完整的示例:
class WebViewExample extends StatefulWidget {
const WebViewExample({super.key});
@override
State<WebViewExample> createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late final WebViewController controller;
@override
void initState() {
super.initState();
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest('your_url');
final platformController = controller.platform;
if (platformController is AndroidWebViewController) {
platformController.setGeolocationPermissionsPromptCallbacks(
onShowPrompt: (request) async {
// request location permission
final locationPermissionStatus = await Permission.locationWhenInUse.request();
// return the response
return GeolocationPermissionsResponse(
allow: locationPermissionStatus == PermissionStatus.granted,
retain: false,
);
},
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: WebViewWidget(
controller: controller,
),
);
}
}