1

我是在旅途中学习颤振的新手,当没有更多的 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")

      ),


    );

  }

}



4

4 回答 4

2

InAppwebview Goback 的工作代码

WillPopScope(
    onWillPop: () {
      setState(() {
        webView.goBack();
      });
    },
于 2020-11-12T13:35:34.013 回答
1

你可以试试我的插件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小部件,其中onWillPophttps://api.flutter.dev/flutter/widgets/WillPopScope/onWillPop.html)我检查 WebView 是否可以返回,否则将弹出当前路线。

于 2019-11-27T23:14:25.373 回答
1

您可以将 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 或堆栈中没有可用的历史记录。

于 2019-11-27T06:16:55.100 回答
0

一个简单的解决方法是将 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;
        },
      ),

    );
  }
于 2020-12-31T23:19:00.013 回答