【问题标题】:How can I make the back button close flutter WebView plugin app on android如何使后退按钮关闭在android上颤动的WebView插件应用程序
【发布时间】:2020-03-22 13:33:55
【问题描述】:

我是在旅途中学习颤振的新手,当没有更多 WebView 返回历史记录时,我正在尝试使用返回按钮关闭我的应用程序。例如,在 WebView 应用程序中,初始 URL 是 google.com,我导航到 yahoo.com,当我按下后退按钮时,它会返回 google.com,如果我再次按下应用程序什么也不做,我希望它在没有时退出更多的历史。我在 Flutter WebView 插件页面上尝试了 CanGoBack() 函数,但在 vscode 中出现错误。我不知道如何实现。

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class WebviewInFlutter extends StatefulWidget {
  WebviewInFlutter({Key key}) : super(key: key);


  @override
  _WebviewInFlutterState createState() => _WebviewInFlutterState();
}

class _WebviewInFlutterState extends State<WebviewInFlutter> {

  final FirebaseMessaging _messaging = FirebaseMessaging();

  @override
  void initState(){

    super.initState();
    _messaging.getToken().then((token) {
      print(token);
    });

    _messaging.configure(
      onMessage: (Map<String, dynamic> message) async{
        print('on message $message');
      },
      onResume: (Map<String, dynamic> message) async{
        print('on resume $message');
      },
      onLaunch: (Map<String, dynamic> message) async{
        print('on launch $message');
      },
    );
    _messaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));

  }
  final flutterWebviewPlugin = new FlutterWebviewPlugin();




  @override
  Widget build(BuildContext context) {

    return WebviewScaffold(
      url: 'https://google.com',
      hidden: true,
      appCacheEnabled: true,
      withJavascript: true,
      withLocalStorage: true,
      appBar: AppBar(
        actions: <Widget>[
              IconButton(
                icon: Icon(Icons.refresh, color: Color.fromRGBO(255, 255, 255, 1.0),),
                onPressed: () => flutterWebviewPlugin.reload(), // this is reloading the url that was provided to webview, not the current URL.
              )
            ],
          elevation: 1.0,
          centerTitle: true,
          title: Text("Google Mobile")

      ),


    );

  }

}



【问题讨论】:

    标签: android flutter flutterwebviewplugin


    【解决方案1】:

    一个简单的解决方法是将 AppBar 添加到脚手架。然后,您的后退按钮功能将像通常在颤振 AppBar 中一样工作。

    @override
      Widget build(BuildContext context) {
        return Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(Icons.arrow_back_sharp),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            title: const Text('Properties Near You'),
            backgroundColor: Colors.green[700],
          ),
    
    
          body: WebView(
            initialUrl: initialUrl,
    
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (webViewController) => _webViewController = webViewController,
            onPageFinished: (String url) {
              if (url == initialUrl) {
                _redirectToStripe(widget.sessionId);
              }
            },
            navigationDelegate: (NavigationRequest request) {
              print(request);
              print(request.url);
              if (request.url.startsWith('http://localhost:5000/success.html')) {
                Navigator.of(context).pop();
                //Navigator.of(context).pushReplacementNamed('/success');
              } else if (request.url.startsWith('http://mykinderpass/cancel')) {
                Navigator.of(context).pop();
                //Navigator.of(context).pushReplacementNamed('/cancel');
              }
              return NavigationDecision.navigate;
            },
          ),
    
        );
      }
    

    【讨论】:

      【解决方案2】:

      InAppwebview Goback 的工作代码

      WillPopScope(
          onWillPop: () {
            setState(() {
              webView.goBack();
            });
          },
      

      【讨论】:

        【解决方案3】:

        你可以试试我的插件flutter_inappbrowser编辑:它已经重命名为flutter_inappwebview)。

        下面是一个例子:

        import 'dart:async';
        
        import 'package:flutter/material.dart';
        
        import 'package:flutter_inappwebview/flutter_inappwebview.dart';
        
        Future main() async {
          runApp(new MyApp());
        }
        
        class MyApp extends StatefulWidget {
          @override
          _MyAppState createState() => new _MyAppState();
        }
        
        class _MyAppState extends State<MyApp> {
        
          @override
          void initState() {
            super.initState();
          }
        
          @override
          void dispose() {
            super.dispose();
          }
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              home: InAppWebViewPage()
            );
          }
        }
        
        class InAppWebViewPage extends StatefulWidget {
          @override
          _InAppWebViewPageState createState() => new _InAppWebViewPageState();
        }
        
        class _InAppWebViewPageState extends State<InAppWebViewPage> {
          InAppWebViewController webView;
        
          @override
          Widget build(BuildContext context) {
            return WillPopScope(
                onWillPop: () async {
                  if (webView != null) {
                    if (await webView.canGoBack()) {
                      // get the webview history
                      WebHistory webHistory = await webView.getCopyBackForwardList();
                      // if webHistory.currentIndex corresponds to 1 or 0
                      if (webHistory.currentIndex <= 1) {
                        // then it means that we are on the first page
                        // so we can exit
                        return true;
                      }
                      webView.goBack();
                      return false;
                    }
                  }
                  return true;
                },
                child: Scaffold(
                    appBar: AppBar(
                        title: Text("InAppWebView")
                    ),
                    body: Container(
                        child: Column(children: <Widget>[
                          Expanded(
                            child: Container(
                              child: InAppWebView(
                                initialUrl: "https://google.com",
                                initialHeaders: {},
                                initialOptions: InAppWebViewWidgetOptions(
                                    inAppWebViewOptions: InAppWebViewOptions(
                                      debuggingEnabled: true,
                                    )
                                ),
                                onWebViewCreated: (InAppWebViewController controller) {
                                  webView = controller;
                                },
                                onLoadStart: (InAppWebViewController controller, String url) {
        
                                },
                                onLoadStop: (InAppWebViewController controller, String url) {
        
                                },
                              ),
                            ),
                          ),
                        ]))
                )
            );
          }
        }
        

        如您所见,它使用WillPopScope 小部件,其中onWillPop (https://api.flutter.dev/flutter/widgets/WillPopScope/onWillPop.html) 我检查WebView 是否可以返回,否则将弹出当前路由。

        【讨论】:

        • 我已经测试了你的代码,但是当我按下 Android 的后退按钮时,它正在关闭应用程序。 (Flutter 1.20.2) (flutter_inappwebview: ^4.0.0+4)
        【解决方案4】:

        您可以将 AppBar 中的后退按钮自定义为

        ..................................
        
        appBar: AppBar(
        leading: new IconButton(
                      icon: new Icon(Icons.arrow_back),
                      onPressed: () {
                        flutterWebviewPlugin.canGoBack().then((value) {
                          if (value) {
                            flutterWebviewPlugin.goBack();
                          } else {
                            Navigator.pop(context);
                          }
                        });
                      }),
        actions: <Widget>[
        
        ..................................
        

        这将检查您是否可以返回 WebView 或堆栈中没有可用的历史记录。

        【讨论】:

        • canGoBack 总是为我返回 false。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多