代码之家  ›  专栏  ›  技术社区  ›  gill

如何在Flutter WebView中使用智能手机上的按钮转到上一页?

  •  0
  • gill  · 技术社区  · 1 年前

    我实现了一个floatingActionButton来移动到上一页,如下面的代码所示。

    是否可以在不使用floatingActionButton的情况下使用智能手机上的后退按钮移动到上一页?

    这是我实现的源代码。

    enter image description here

    enter image description here

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    
    final uri = Uri.parse('https://google.com');
    
    class HomeScreen extends StatelessWidget {
      WebViewController controller = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setNavigationDelegate(NavigationDelegate(
          onPageFinished: (String url){
            print(url);
          }
        ))
        ..loadRequest(uri);
    
      HomeScreen({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
    
          floatingActionButton: Container(
            height: 40.0,
            width: 40.0,
            child: FittedBox(
            child: FloatingActionButton(
            child: Icon(Icons.arrow_back),
            onPressed: () => controller?.goBack(),
            backgroundColor:  Colors.grey.shade200,
          ),
          ),
          ),
    
          body: SafeArea(
            child : WebViewWidget(
            controller: controller,
            ),
          ),
        );
      }
    }
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Amir Rahimian    1 年前

    要管理Flutter中的后退键按下,可以作为拖动手势,也可以使用->img中的按钮:

    PopScope

    PopScope(
      canPop: /* BOOL VALUE THAT CHECK IF ITS OK TO CLOSE APP OR NOT , YOU MAY PASS FALSE:)*/ false ,
      onPopInvoked: (didPop) {
        //FUNCTION THAT CALL WHEN EVER THE BACK CLICKED :) 
        controller?.goBack();
      },
      child: Scaffold(
      
        floatingActionButton: Container(
          height: 40.0,
          width: 40.0,
          child: FittedBox(
            child: FloatingActionButton(
              child: Icon(Icons.arrow_back),
              onPressed: () => controller?.goBack(),
              backgroundColor:  Colors.grey.shade200,
            ),
          ),
        ),
      
        body: SafeArea(
          child : WebViewWidget(
            controller: controller,
          ),
        ),
      ),
    );
    

    不赞成 ! WillPopScope 也可以工作

    “WillPopScope”已弃用,不应使用。请改用PopScope。此功能在3.12.0-1.0.pre版本之后已被弃用。( Documentation )

    我希望它能帮助你:)