6

使用下面的代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: const MyHomePage(),
      );
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) => DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: const Center(
            child: Text('use the mouse wheel to scroll')),
            bottom: TabBar(
              tabs: const [
                Center(child: Text('ScrollView')),
                Center(child: Text('PageView'))
              ],
            ),
          ),
          body: TabBarView(
            children: [
              SingleChildScrollView(
                child: Column(
                  children: [
                    for (int i = 0; i < 10; i++)
                      Container(
                        height: MediaQuery.of(context).size.height,
                        child: const Center(
                          child: FlutterLogo(size: 80),
                        ),
                      ),
                  ],
                ),
              ),
              PageView(
                scrollDirection: Axis.vertical,
                children: [
                  for (int i = 0; i < 10; ++i)
                    const Center(
                      child: FlutterLogo(size: 80),
                    ),
                ],
              ),
            ],
          ),
        ),
      );
}

你可以看到,在dartpad或从这个视频中运行它,

使用鼠标滚轮滚动 aPageView提供平庸的体验(充其量),

这是一个已知问题#35687 #32120,但我正在尝试找到解决方法

实现平滑滚动PageView或至少防止“口吃”。

有人可以帮助我或指出我正确的方向吗?

我不确定问题出在PageScrollPhysics;

我有一种直觉,问题可能出在WheelEvent 上

因为使用多点触控滚动滑动非常有效

4

4 回答 4

4

问题源于一系列事件:

  1. 用户将鼠标滚轮旋转一格,
  2. Scrollable接收PointerSignal调用 jumpTo方法,
  3. _PagePositionjumpTo方法(派生自ScrollPositionWithSingleContext)更新滚动位置并调用goBallistic方法,
  4. 模拟请求PageScrollPhysics位置恢复为初始值,因为一个缺口偏移量太小而无法翻页,
  5. 从步骤(1)重复另一个凹口和过程。

解决问题的一种方法是在调用goBallistic方法之前执行延迟。这可以在_PagePosition类中完成,但是类是私有的,我们必须修补 Flutter SDK:

// <FlutterSDK>/packages/flutter/lib/src/widgets/page_view.dart
// ...

class _PagePosition extends ScrollPositionWithSingleContext implements PageMetrics {
  //...

  // add this code to fix issue (mostly borrowed from ScrollPositionWithSingleContext):
  Timer timer;

  @override
  void jumpTo(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
    }
    if (timer != null) timer.cancel();
    timer = Timer(Duration(milliseconds: 200), () {
      goBallistic(0.0);
      timer = null;
    });
  }

  // ...
}

另一种方法是将 jumpTo 替换为 animateTo。这可以在不修补 Flutter SDK 的情况下完成,但看起来更复杂,因为我们需要禁用默认PointerSignalEvent侦听器:

import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class PageViewLab extends StatefulWidget {
  @override
  _PageViewLabState createState() => _PageViewLabState();
}

class _PageViewLabState extends State<PageViewLab> {
  final sink = StreamController<double>();
  final pager = PageController();

  @override
  void initState() {
    super.initState();
    throttle(sink.stream).listen((offset) {
      pager.animateTo(
        offset,
        duration: Duration(milliseconds: 200),
        curve: Curves.ease,
      );
    });
  }

  @override
  void dispose() {
    sink.close();
    pager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mouse Wheel with PageView'),
      ),
      body: Container(
        constraints: BoxConstraints.expand(),
        child: Listener(
          onPointerSignal: _handlePointerSignal,
          child: _IgnorePointerSignal(
            child: PageView.builder(
              controller: pager,
              scrollDirection: Axis.vertical,
              itemCount: Colors.primaries.length,
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(color: Colors.primaries[index]),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Stream<double> throttle(Stream<double> src) async* {
    double offset = pager.position.pixels;
    DateTime dt = DateTime.now();
    await for (var delta in src) {
      if (DateTime.now().difference(dt) > Duration(milliseconds: 200)) {
        offset = pager.position.pixels;
      }
      dt = DateTime.now();
      offset += delta;
      yield offset;
    }
  }

  void _handlePointerSignal(PointerSignalEvent e) {
    if (e is PointerScrollEvent && e.scrollDelta.dy != 0) {
      sink.add(e.scrollDelta.dy);
    }
  }
}

// workaround https://github.com/flutter/flutter/issues/35723
class _IgnorePointerSignal extends SingleChildRenderObjectWidget {
  _IgnorePointerSignal({Key key, Widget child}) : super(key: key, child: child);

  @override
  RenderObject createRenderObject(_) => _IgnorePointerSignalRenderObject();
}

class _IgnorePointerSignalRenderObject extends RenderProxyBox {
  @override
  bool hitTest(BoxHitTestResult result, {Offset position}) {
    final res = super.hitTest(result, position: position);
    result.path.forEach((item) {
      final target = item.target;
      if (target is RenderPointerListener) {
        target.onPointerSignal = null;
      }
    });
    return res;
  }
}

这是CodePen 上的演示。

于 2020-09-02T13:16:30.900 回答
2

非常相似但更容易设置:

smooth_scroll_web ^0.0.4添加到您的pubspec.yaml

...
dependencies:
    ...
    smooth_scroll_web: ^0.0.4
...

用法:

import 'package:smooth_scroll_web/smooth_scroll_web.dart';
import 'package:flutter/material.dart';
import 'dart:math'; // only for demo

class Page extends StatefulWidget {
  @override
  PageState createState() => PageState();
}

class PageState extends State<Page> {
  final ScrollController _controller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SmoothScroll Example"),
      ),
      body: SmoothScrollWeb(
        controller: controller,
        child: Container(
            height: 1000,
            child: ListView(
              physics: NeverScrollableScrollPhysics(),
              controller: _controller,
              children: [
                // Your content goes here, thoses children are only for demo
                for (int i = 0; i < 100; i++)
                  Container(
                    height: 60,
                    color: Color.fromARGB(1, 
                      Random.secure().nextInt(255),
                      Random.secure().nextInt(255),
                      Random.secure().nextInt(255)),
                  ),
              ],
            ),
          ),
      ),
    );
  }
}

谢谢你的业余爱好者

参考Flutter 在 Github 上的 issue #32120

于 2021-04-09T18:43:10.593 回答
0

问题在于用户设置,最终用户如何设置滚动以使用鼠标进行。我有一个罗技鼠标,它允许我通过罗技选项打开或关闭平滑滚动功能。当我启用平滑滚动时,它可以完美地工作并根据需要滚动,但如果禁用平滑滚动,它也会在项目中被禁用。行为由最终用户设置。

尽管如此,如果需要强制滚动平滑滚动,则只能通过设置相关动画来完成。目前还没有直接的方法。

在此处输入图像描述

于 2020-08-29T20:17:44.273 回答
0

我知道这个问题已经过去了将近 1.5 年,但我找到了一种运行顺利的方法。也许这对阅读它的人很有帮助。使用此代码向您的页面浏览控制器添加一个侦听器(您可以对持续时间或 nextPage/animateToPage/jumpToPage 等进行调整):

pageController.addListener(() {
  if (pageController.position.userScrollDirection == ScrollDirection.reverse) {
    pageController.nextPage(duration: const Duration(milliseconds: 60), curve: Curves.easeIn);
  } else if (pageController.position.userScrollDirection == ScrollDirection.forward) {
    pageController.previousPage(duration: const Duration(milliseconds: 60), curve: Curves.easeIn);
  }
});
于 2022-02-27T21:06:54.817 回答