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

问题描述 投票:0回答:1

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

是否可以使用智能手机上的后退按钮移至上一页而不使用浮动操作按钮?

这是我实现的源代码。

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,
        ),
      ),
    );
  }
}
flutter webview
1个回答
0
投票

要在 Flutter 中管理后退按键,可以通过拖动手势或使用图片中的 -> 按钮来实现:

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。此功能在 v3.12.0-1.0.pre 之后已弃用。 (文档

希望对你有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.