I’m developing a Flutter app (with GetX) where I need WebView somewhere. I’m sharing my code below which works perfectly for Android devices but not in iOS simulator. I still couldn’t detect the problem.
class VirtualCardController extends GetxController {
/* other codes */
late final WebViewController controller;
/* other codes */
@override
void onInit() {
super.onInit();
var params = const PlatformWebViewControllerCreationParams();
if (WebViewPlatform.instance is WebKitWebViewPlatform) {
params = WebKitWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(params);
} else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
params = AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(params);
}
controller = WebViewController.fromPlatformCreationParams(params);
}
void _loadWebView(String url) {
// Ensure the URL has a scheme
if (url.isEmpty) {
url = 'https://www.google.com/';
} else if (!url.startsWith('https://') && !url.startsWith('http://')) {
url = 'https://$url';
}
controller
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onHttpError: (HttpResponseError error) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(url)).then((_) {
isLoading.value = false;
});
}
/* other codes */
}
Note that I have added these in pubspec.yaml:
- webview_flutter: ^4.8.0
- webview_flutter_android: ^3.16.4
- webview_flutter_wkwebview: ^3.14.0