簡體   English   中英

我想檢測 WebView_Flutter 中的滾動並隱藏填充

[英]I want to detect scrolling in WebView_Flutter and hide the padding

我正在使用 Webview_Flutter。 該網站的 header 與狀態欄的 position 重疊,我想添加填充以避免這種情況。

如果打開 webview 或者頂部有滾動條 position,這是插入填充以避免狀態欄的過程。

    body: Padding(
          padding: (controller?.getScrollY() == null || controller?.getScrollY() == 0)
              ? EdgeInsets.only(top: height)
              : EdgeInsets.only(top: 0),
          child: Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 0.0),
                      child: WebView(
                        javascriptMode: JavascriptMode.unrestricted,
                        initialUrl: Uri.parse(widget.link).toString(),
                        onWebResourceError: (error) {
                          // print(error.domain);
                        },
                        onWebViewCreated: (controller) {
                          this.controller = controller;
                        },
                        onProgress: (progress) {
                          setState(() {
                            this.progress = progress / 100;
                            progressPercent = progress;
                          });
                        },
                      ),
              

要檢測 WebView 滾動事件,可以使用flutter_inappwebview插件(我是作者)並實現InAppWebView.onScrollChanged事件。

但是,您可能不需要為 WebView 添加頂部填充。您可以將AppBar.toolbarHeight設置為0 ,這樣應用欄的高度就會覆蓋狀態欄。

這是一個完整的代碼示例,兩種情況都使用插件的當前最新版本 6 ( 6.0.0-beta.16 ):

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (!kIsWeb &&
      kDebugMode &&
      defaultTargetPlatform == TargetPlatform.android) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
  }
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;

  int scrollY = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          toolbarHeight: 0,
        ),
        body: Padding(
          padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),
          child: Column(
            children: [
              Expanded(
                child: InAppWebView(
                  key: webViewKey,
                  initialUrlRequest:
                      URLRequest(url: WebUri("https://github.com/flutter")),
                  onWebViewCreated: (controller) {
                    webViewController = controller;
                  },
                  onScrollChanged: (controller, x, y) {
                    setState(() {
                      scrollY = y;
                    });
                  },
                ),
              )
            ],
          ),
        ));
  }
}

模擬器屏幕錄制 - iPhone 14 Pro Max - 2022-11-25 at 01 21 15

我試圖找到 webView 卷軸的監聽器,我找不到它,你是對的。 有一個解決方案^^,很簡單,我們可以在 ListView 中包裝 WebView 然后我們可以使用 scrollListener(1) 或 notificationListener(2) 並且不要忘記使用 setState 來更新 Padding 值

class _HomeScreenState extends State<HomeScreen> {
    WebViewController? _webViewController;
    ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        body:Scaffold(
          backgroundColor: Colors.green,
          appBar: AppBar(
            title: const Text('Flutter WebView example'),
            // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
            actions: <Widget>[

            ],
          ),
//NotificationListener(2)
          body: NotificationListener<ScrollNotification>(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollStartNotification) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              print("ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}");
            });

          } else if (scrollNotification is ScrollEndNotification) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              setState(() {
                print("ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}");
              });
            });
          }

              return true;
            },
            child: ListView(
              physics: ClampingScrollPhysics(),
              controller: _scrollController,
              children: <Widget>[
                ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 10000),
                    child: WebView(
                      initialUrl: 'https://flutter.dev',
                      javascriptMode: JavascriptMode.unrestricted,
                      onWebViewCreated: (WebViewController webViewController) {},
                      onProgress: (int progress) {
                        print('WebView is loading (progress : $progress%)');
                      },
                      javascriptChannels: <JavascriptChannel>{
                      },
                      onPageStarted: (String url) {},
                      onPageFinished: (String url) {},
                      gestureNavigationEnabled: true,
                      backgroundColor: const Color(0x00000000),
                    ),
                ),
              ],
            ),
          )));


  }

    @override
  void initState() {
     super.initState();
//scrollListener(1)
     _scrollController.addListener(() {
       print("scrollListener / pixel =>${_scrollController.position.pixels}");
     });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM