Flutter上拉抽屜實現

我們在APP中經常可以看到各種抽屜,比如:某音的評論以及經典的豆瓣評論。這種抽屜效果,都是十分好看經典的設計。
但是在flutter中,只有側邊抽屜,沒看到有上拉的抽屜。項目中UI需要下面的效果:

Flutter抽屜

本文更多是傳遞flutter學習與開發自定義Widget的一個思想。能夠更好的理解Flutter的GestureRecognizer、Transform、AnimationController等等

分析

遇到一個問題或者需求,我更建議大家把需求細化,細分。然后逐個分析,個個擊破。

  • 抽屜里存放列表數據。上拉小于一定值 ,自動回彈到底部
  • 當抽屜未到達頂部時,上拉列表,抽屜上移。
  • 當抽屜到到達頂部時,上拉列表,抽屜不動,列表數據移動。
  • 抽屜的列表數據,下拉時,出現最后一條數據時,整個抽屜隨之下拉
  • 抽屜上拉時,有一個向上的加速度時,手指離開屏幕,抽屜會自動滾到頂部

解決方案

GestureRecognizer

母庸質疑,這里涉及到更多的是監聽手勢。監聽手指按下、移動、抬起以及加速度移動等。這些,通過flutter強大的GestureRecognizer就可以搞定。

Flutter Gestures 中簡單來說就是可以監聽用戶的以下手勢:

  • Tap

    • onTabDown 按下
    • onTapUp 抬起
    • onTap 點擊
    • onTapCancel
  • Double tap 雙擊

  • Vertical drag 垂直拖動屏幕

    • onVerticalDragStart
    • onVerticalDragUpdate
    • onVerticalDragEnd
  • Horizontal drag 水平拖動屏幕

    • onHorizontalDragStart
    • onHorizontalDragUpdate
    • onHorizontalDragEnd
  • Pan

    • onPanStart 可能開始水平或垂直移動。如果設置了onHorizontalDragStart或onVerticalDragStart回調,則會導致崩潰 。
    • onPanUpdate 觸摸到屏幕并在垂直或水平方移動。如果設置了onHorizontalDragUpdate或onVerticalDragUpdate回調,則會導致崩潰 。
    • onPanEnd 在停止接觸屏幕時以特定速度移動。如果設置了onHorizontalDragEnd或onVerticalDragEnd回調,則會導致崩潰 。

每個行為,均有著對應的Recognizer去處理。

分別對應著下面:

GestureRecognizer

在這里我們用到的就是VerticalDragGestureRecognizer,用來監聽控件垂直方向接收的行為。

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

class BottomDragWidget extends StatefulWidget {
  @override
  _BottomDragWidgetState createState() => _BottomDragWidgetState();
}

class _BottomDragWidgetState extends State<BottomDragWidget> {
  @override
  Widget build(BuildContext context) {
    return Stack(children: <Widget>[
      Align(
        alignment: Alignment.bottomCenter,
        child: DragContainer(),
      )
    ],);
  }
}

class DragContainer extends StatefulWidget {
  @override
  _DragContainerState createState() => _DragContainerState();
}

class _DragContainerState extends State<DragContainer> {
  double offsetDistance = 0.0;

  @override
  Widget build(BuildContext context) {
    ///使用Transform.translate 移動drag的位置
    return Transform.translate(
      offset: Offset(0.0, offsetDistance),
      child: RawGestureDetector(
        gestures: {MyVerticalDragGestureRecognizer: getRecognizer()},
        child: Container(
          width: 100.0,
          height: 100.0,
          color: Colors.brown,
        ),
      ),
    );
  }

  GestureRecognizerFactoryWithHandlers<MyVerticalDragGestureRecognizer>
      getRecognizer() {
    return GestureRecognizerFactoryWithHandlers(
        () => MyVerticalDragGestureRecognizer(), this._initializer);
  }

  void _initializer(MyVerticalDragGestureRecognizer instance) {
    instance
      ..onStart = _onStart
      ..onUpdate = _onUpdate
      ..onEnd = _onEnd;
  }

  ///接受觸摸事件
  void _onStart(DragStartDetails details) {
    print('觸摸屏幕${details.globalPosition}');
  }

  ///垂直移動
  void _onUpdate(DragUpdateDetails details) {
    print('垂直移動${details.delta}');
    offsetDistance = offsetDistance + details.delta.dy;
    setState(() {});
  }

  ///手指離開屏幕
  void _onEnd(DragEndDetails details) {
    print('離開屏幕');
  }
}

class MyVerticalDragGestureRecognizer extends VerticalDragGestureRecognizer {
  MyVerticalDragGestureRecognizer({Object debugOwner})
      : super(debugOwner: debugOwner);
}


3.gif

很簡單的,我們就完成了widget跟隨手指上下移動。

使用動畫

之前我們有說道,當我們松開手時,控件會自動跑到最下面,或者跑到最頂端。這里呢,我們就需要使用到AnimationController

 animalController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 250));

///easeOut 先快后慢
    final CurvedAnimation curve =
        new CurvedAnimation(parent: animalController, curve: Curves.easeOut);
    animation = Tween(begin: start, end: end).animate(curve)
      ..addListener(() {
        offsetDistance = animation.value;
          setState(() {});
      });

    ///自己滾動
    animalController.forward();

33.gif

在手指離開屏幕的回調方法中,在void _onEnd(DragEndDetails details)使用animalController,也就是當手指離開屏幕,將上層的DragContainer歸到原位。

到這里,已經解決了。滾動,自動歸位。下一步,就是解決比較困難的情況。

解決嵌套列表數據

在抽屜中,我們經常存放的是列表數據。所以,會有下面的情況:

列表數據

也就是說,在下拉列表時,只有第一條顯示后,整個DragContainer才會隨之下移。但是在Flutter中,并沒有可以判斷顯示第一條數據的回調監聽。但是官方,有NotificationListener,用來進行滑動監聽的。

ScrollNotification

  • ScrollStartNotification 部件開始滑動
  • ScrollUpdateNotification 部件位置發生改變
  • OverscrollNotification 表示窗口小部件未更改它的滾動位置,因為更改會導致滾動位置超出其滾動范圍
  • ScrollEndNotification 部件停止滾動

可以有童鞋有疑問,為什么使用監聽垂直方向的手勢去移動位置,而不用 ScrollUpdateNotification去更新DragContainer的位置。這是因為:ScrollNotification這個東西是一個滑動通知,他的通知是有延遲!
的。官方有說:Any attempt to adjust the build or layout based on a scroll notification would result in a layout that lagged one frame behind, which is a poor user experience.

也就是說,我們可以將DragContainer放在NotificationListener中,當觸發了ScrollEndNotification的時候,也就是說整個列表數據需要向下移動了。


///在ios中,默認返回BouncingScrollPhysics,對于[BouncingScrollPhysics]而言,
///由于   double applyBoundaryConditions(ScrollMetrics position, double value) => 0.0;
///會導致:當listview的第一條目顯示時,繼續下拉時,不會調用上面提到的Overscroll監聽。
///故這里,設定為[ClampingScrollPhysics]
class OverscrollNotificationWidget extends StatefulWidget {
  const OverscrollNotificationWidget({
    Key key,
    @required this.child,
//    this.scrollListener,
  })  : assert(child != null),
        super(key: key);

  final Widget child;
//  final ScrollListener scrollListener;

  @override
  OverscrollNotificationWidgetState createState() =>
      OverscrollNotificationWidgetState();
}

/// Contains the state for a [OverscrollNotificationWidget]. This class can be used to
/// programmatically show the refresh indicator, see the [show] method.
class OverscrollNotificationWidgetState
    extends State<OverscrollNotificationWidget>
    with TickerProviderStateMixin<OverscrollNotificationWidget> {
  final GlobalKey _key = GlobalKey();

  ///[ScrollStartNotification] 部件開始滑動
  ///[ScrollUpdateNotification] 部件位置發生改變
  ///[OverscrollNotification] 表示窗口小部件未更改它的滾動位置,因為更改會導致滾動位置超出其滾動范圍
  ///[ScrollEndNotification] 部件停止滾動
  ///之所以不能使用這個來build或者layout,是因為這個通知的回調是會有延遲的。
  ///Any attempt to adjust the build or layout based on a scroll notification would
  ///result in a layout that lagged one frame behind, which is a poor user experience.

  @override
  Widget build(BuildContext context) {
    print('NotificationListener build');
    final Widget child = NotificationListener<ScrollStartNotification>(
      key: _key,
      child: NotificationListener<ScrollUpdateNotification>(
        child: NotificationListener<OverscrollNotification>(
          child: NotificationListener<ScrollEndNotification>(
            child: widget.child,
            onNotification: (ScrollEndNotification notification) {
              _controller.updateDragDistance(
                  0.0, ScrollNotificationListener.end);
              return false;
            },
          ),
          onNotification: (OverscrollNotification notification) {
            if (notification.dragDetails != null &&
                notification.dragDetails.delta != null) {
              _controller.updateDragDistance(notification.dragDetails.delta.dy,
                  ScrollNotificationListener.edge);
            }
            return false;
          },
        ),
        onNotification: (ScrollUpdateNotification notification) {
          return false;
        },
      ),
      onNotification: (ScrollStartNotification scrollUpdateNotification) {
        _controller.updateDragDistance(0.0, ScrollNotificationListener.start);
        return false;
      },
    );

    return child;
  }
}

enum ScrollNotificationListener {
  ///滑動開始
  start,

  ///滑動結束
  end,

  ///滑動時,控件在邊緣(最上面顯示或者最下面顯示)位置
  edge
}

通過這個方案,我們就解決了列表數據的問題。最后一個問題,當手指快速向上滑動的時候然后松開手的時候,讓列表數據自動滾動頂端。這個快速上滑,如何解決。

dragContainer中使用的是ScrollView,一定要將physics的值設定為ClampingScrollPhysics,否則不能監聽到ScrollEndNotification。這是平臺不一致性導致的。在scroll_configuration.dart中,有這么一段:

scroll_configuration

判斷Fling

對于這個,是我在由項目需求,魔改源碼的時候,無意中看到的。所以需要翻源碼了。在DragGestureRecognizer中,官方有一個也是判斷Filing的地方,

_isFlingGesture

不過這個方法是私有的,我們無法調用。(雖然dart可以反射,但是不建議。),我們就按照官方的思路一樣的寫就好了。


///MyVerticalDragGestureRecognizer 負責任務
///1.監聽child的位置更新
///2.判斷child在手松的那一刻是否是出于fling狀態
class MyVerticalDragGestureRecognizer extends VerticalDragGestureRecognizer {
  final FlingListener flingListener;

  /// Create a gesture recognizer for interactions in the vertical axis.
  MyVerticalDragGestureRecognizer({Object debugOwner, this.flingListener})
      : super(debugOwner: debugOwner);

  final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{};

  @override
  void handleEvent(PointerEvent event) {
    super.handleEvent(event);
    if (!event.synthesized &&
        (event is PointerDownEvent || event is PointerMoveEvent)) {
      final VelocityTracker tracker = _velocityTrackers[event.pointer];
      assert(tracker != null);
      tracker.addPosition(event.timeStamp, event.position);
    }
  }

  @override
  void addPointer(PointerEvent event) {
    super.addPointer(event);
    _velocityTrackers[event.pointer] = VelocityTracker();
  }

  ///來檢測是否是fling
  @override
  void didStopTrackingLastPointer(int pointer) {
    final double minVelocity = minFlingVelocity ?? kMinFlingVelocity;
    final double minDistance = minFlingDistance ?? kTouchSlop;
    final VelocityTracker tracker = _velocityTrackers[pointer];

    ///VelocityEstimate 計算二維速度的
    final VelocityEstimate estimate = tracker.getVelocityEstimate();
    bool isFling = false;
    if (estimate != null && estimate.pixelsPerSecond != null) {
      isFling = estimate.pixelsPerSecond.dy.abs() > minVelocity &&
          estimate.offset.dy.abs() > minDistance;
    }
    _velocityTrackers.clear();
    if (flingListener != null) {
      flingListener(isFling);
    }

    ///super.didStopTrackingLastPointer(pointer) 會調用[_handleDragEnd]
    ///所以將[lingListener(isFling);]放在前一步調用
    super.didStopTrackingLastPointer(pointer);
  }

  @override
  void dispose() {
    _velocityTrackers.clear();
    super.dispose();
  }
}

好的,這就解決了Filing的判斷。

最后效果

part1.gif
part2.gif

模擬器有點卡~

源碼地址

博客地址

Flutter 豆瓣客戶端,誠心開源
Flutter 豆瓣客戶端,誠心開源
Flutter Container
Flutter SafeArea
Flutter Row Column MainAxisAlignment Expanded
Flutter Image全解析
Flutter 常用按鈕總結
Flutter ListView豆瓣電影排行榜
Flutter Card
Flutter Navigator&Router(導航與路由)
OverscrollNotification不起效果引起的Flutter感悟分享
Flutter 上拉抽屜實現

Flutter 更改狀態欄顏色

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,362評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,577評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,486評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,852評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,600評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,944評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,944評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,108評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,652評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,385評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,616評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,111評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,798評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,205評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,537評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,334評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,570評論 2 379