如何使用“ webview_flutter”获取偏移量?

时间:2019-11-22 09:47:26

标签: flutter dart

我想要的是下拉Webview页面时隐藏SliverAppBar,将Webview页面拉至顶部时显示SliverAppBar,我将Webview与CustomScrollView&SliverAppBar&SliverFillRemaining结合在一起,我认为这是有效的。但是我需要监听webview偏移量以控制SliverAppBar。

代码:

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewGestureRecognizer extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new WebviewGestureRecognizerState();
}

class WebviewGestureRecognizerState extends State<WebviewGestureRecognizer> {

  ScrollController _controller = new ScrollController();

  WebViewController wvController;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      // here is the CustomScrollView offset
      print(_controller.offset);
    });
  }

  hideAppBar() {
    _controller.animateTo(100.0,
        duration: new Duration(milliseconds: 1000), curve: Curves.linear);
  }

  showAppBar() {
    _controller.animateTo(0.0,
        duration: new Duration(milliseconds: 1000), curve: Curves.linear);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: CustomScrollView(
        controller: _controller,
        slivers: <Widget>[
          SliverAppBar(
            title: const Text("webview GuesureRecognizer"),
            floating: true,
          ),
          SliverFillRemaining(
            hasScrollBody: true,
            fillOverscroll: false,
            child: WebView(
              debuggingEnabled: true,
              javascriptMode: JavascriptMode.unrestricted,
              gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
                new Factory<OneSequenceGestureRecognizer>(
                  () => CustomGestureWidget(),
                ),
              ].toSet(),
              onWebViewCreated: (WebViewController webViewController) {
                webViewController.loadUrl(
                  "https://www.qq.com",
                );
                wvController = webViewController;
              },
            ),
          ),
        ],
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

哦,我忘了上课:

class CustomGestureWidget extends OneSequenceGestureRecognizer {
  CustomGestureWidget({PointerDeviceKind kind}) : super(kind: kind);

  @override
  void addAllowedPointer(PointerDownEvent event) {
    print("PointerDownEvent: $event");
    startTrackingPointer(event.pointer, event.transform);
    resolve(GestureDisposition.accepted);
    stopTrackingPointer(event.pointer);
  }

  @override
  String get debugDescription => 'eager';

  @override
  void didStopTrackingLastPointer(int pointer) {
    print("pointer: $pointer");
  }

  @override
  void handleEvent(PointerEvent event) {
    print("event: $event");
  }
}