简体   繁体   English

Flutter (webview_flutter) 滑动返回 Pop Webview

[英]Flutter (webview_flutter) Swipe Back to Pop Webview

I use the below code for a Flutter Webview (webview_flutter package).我将以下代码用于 Flutter Webview(webview_flutter 包)。

When a Back button is clicked, _goBack() sets whether to go back to the previous page, or if no previous page, pops the webview.单击返回按钮时,_goBack() 设置是否将 go 返回上一页,或者如果没有上一页,则弹出 webview。

I then enabled gestureNavigationEnabled:true to allow the user to swipe back to previous pages.然后我启用了gestureNavigationEnabled:true 以允许用户滑回之前的页面。 Works well.效果很好。 However, when there are no previous pages, swiping does not pop the webview.但是,当没有以前的页面时,刷卡不会弹出 webview。

Is there a way to give swiping back the same behavior as the Back button ?有没有办法让向后滑动与返回按钮相同的行为?

  1. if previous page exists, swipes to the previous page如果上一页存在,则滑动到上一页
  2. if no previous page, swipe closes the webview如果没有上一页,滑动关闭 webview

Thank you.谢谢你。

import 'package:webview_flutter/webview_flutter.dart';

     body: WillPopScope(
      onWillPop: () => _goBack(context),
      child: WebView(  
        initialUrl: widget.url,
        gestureNavigationEnabled: true,
        onWebViewCreated: (WebViewController webViewController) {
          _controllerCompleter.future.then((value) => _controller = value);
          _controllerCompleter.complete(webViewController);
      ),
    ),

      Future<bool> _goBack(BuildContext context) async {
        if (await _controller.canGoBack()) {
          _controller.goBack();
          return Future.value(false);
        } else {
          Navigator.of(context).pop();
          return Future.value(true);
        }
      }

The Problem is the 'Context' when it found no context it doesnt close the webview window.so in this case what you need to do is:问题是“上下文”,当它发现没有上下文时它没有关闭 webview window.so 在这种情况下你需要做的是:

Look at this here: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074看这里: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074

You can set a global key for your navigation:

    final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

Pass it to MaterialApp:

    new MaterialApp(
          title: 'MyApp',
          onGenerateRoute: generateRoute,
          navigatorKey: navigatorKey,
        );

Push routes:

    navigatorKey.currentState.pushNamed('/someRoute');

You Need to Create a Global Key for Navigation and then it can work.您需要为导航创建一个全局键,然后它才能工作。 it will close the window without getting the context (means if the previous page is not there then it can also pop the window )它将关闭 window 而不获取上下文(意味着如果上一页不存在,那么它也可以弹出 window )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM