skip to Main Content

Can you tell me how can I go back to previous pages in my webview application?

I am using the following code which works for android but not swipe on iphone –

late WebViewController? webViewController;

   Future<bool> _onWillPop(BuildContext context) async {
     if (await webViewController!.canGoBack()) {
       webViewController!.goBack();
       return Future value(false);
     } else {
       return Future value(true);
     }
   }

and here is my complete widget code –

return WillPopScope(
        child: Scaffold(
          bottomNavigationBar: BottomNavigationBar(
              selectedItemColor: Colors.orange,
              backgroundColor: Colors.white,
              type: BottomNavigationBarType.fixed,
              currentIndex: selectedIndex,
              unselectedLabelStyle: TextStyle(color: Color.fromARGB(153, 162, 173, 1)),
              selectedLabelStyle: TextStyle(fontSize: 11.9),
              items: [
                BottomNavigationBarItem(
                  icon: Container(margin: EdgeInsets.only(bottom: 5), height: 32, width: 35, child: Image.asset('assets/images/Home.png', fit: BoxFit.cover,),),
                  activeIcon: Container(margin: EdgeInsets.only(bottom: 5),height: 32, width: 35, child: Image.asset('assets/images/Home_color.png', fit: BoxFit.cover,),),
                  label: "Главная"
                ),
                BottomNavigationBarItem(
                  icon: Container(margin: EdgeInsets.only(bottom: 5),height: 32, width: 32, child: Image.asset('assets/images/Catalog.png', fit: BoxFit.cover,)),
                  activeIcon: Container(margin: EdgeInsets.only(bottom: 5),height: 32, width: 32, child: Image.asset('assets/images/Catalog_color.png', fit: BoxFit.cover,),),
                  label: "Каталог",
                ),
              ],
              onTap: (i) async {
                webViewController?.loadUrl(linkNavbar[i]);
                setState(() => selectedIndex = i);
              },
            ),
          body: SafeArea(
            child: Stack(
                children: [
                  WebView(
                    key: _key,
                    javascriptMode: JavascriptMode.unrestricted,
                    initialUrl: "https://caravan-store.shop/",
                    onWebViewCreated: (controller) {
                      setState(() {
                        webViewController = controller;
                      });
                    },
                    onWebResourceError: (WebResourceError error) {
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(
                          builder: (context) => MyError(),
                        ),
                      );
                    },
                  ),
        
                ]
            ),
          )
        ),
          onWillPop: () => _onWillPop(context)
    );

Also, I added this code to my main.dart –

theme: ThemeData(
    pageTransitionsTheme: PageTransitionsTheme(
      builders: {
        TargetPlatform.android: CupertinoPageTransitionsBuilder(),
        TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
      }
    )

On the Internet, I could not find any solution for such a problem. What I’m doing is trying to make a swipe to the right to go to the previous page. Unfortunately, it doesn’t work on iPhone, but it works on Android.

Tell me what do I need to do?

2

Answers


  1. Chosen as BEST ANSWER

    To be honest, I don't know why it worked, but by adding the following code, everything worked on the iPhone.

    WebView(
                      key: _key,
                      javascriptMode: JavascriptMode.unrestricted,
                      initialUrl: "link",
                      gestureNavigationEnabled: true, //this
    

  2. Its work android and ios both right now

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    import 'package:webview_flutter_android/webview_flutter_android.dart';
    import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
    
    class WebExample extends StatefulWidget {
      const WebExample({Key? key}) : super(key: key);
    
      @override
      State<WebExample> createState() => _WebExampleState();
    }
    
    class _WebExampleState extends State<WebExample> {
      late final WebViewController _controller;
    
      @override
      void initState() {
        super.initState();
    
        // #docregion platform_features
        late final PlatformWebViewControllerCreationParams params;
        if (WebViewPlatform.instance is WebKitWebViewPlatform) {
          params = WebKitWebViewControllerCreationParams(
            allowsInlineMediaPlayback: true,
            mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
          );
        } else {
          params = const PlatformWebViewControllerCreationParams();
        }
    
        final WebViewController controller =
            WebViewController.fromPlatformCreationParams(params);
        // #enddocregion platform_features
    
        controller
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setBackgroundColor(const Color(0x00000000))
          ..setNavigationDelegate(
            NavigationDelegate(
              onNavigationRequest: (NavigationRequest request) {
                if (request.url.startsWith('https://www.youtube.com/')) {
                  debugPrint('blocking navigation to ${request.url}');
                  return NavigationDecision.prevent;
                }
                debugPrint('allowing navigation to ${request.url}');
                return NavigationDecision.navigate;
              },
              onUrlChange: (UrlChange change) {
                debugPrint('url change to ${change.url}');
              },
            ),
          )
          ..addJavaScriptChannel(
            'Toaster',
            onMessageReceived: (JavaScriptMessage message) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text(message.message)),
              );
            },
          )
          ..loadRequest(Uri.parse('https://flutter.dev'));
    
        // #docregion platform_features
        if (controller.platform is AndroidWebViewController) {
          AndroidWebViewController.enableDebugging(true);
          (controller.platform as AndroidWebViewController)
              .setMediaPlaybackRequiresUserGesture(false);
        }
    
        _controller = controller;
      }
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () => _backPressed2(_controller, context),
          child: Scaffold(
            body: WebViewWidget(controller: _controller),
          ),
        );
      }
    }
    
    Future<bool> _backPressed2(
        WebViewController webViewController, BuildContext context) async {
      if (await webViewController.canGoBack()) {
        await webViewController.goBack();
      } else {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('No back history item')),
          );
        }
      }
      return Future<bool>.value(false);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search