Flutter上拉抽屜實(shí)現(xiàn)

我們?cè)贏PP中經(jīng)秤詹常可以看到各種抽屜,比如:某音的評(píng)論以及經(jīng)典的豆瓣評(píng)論谈况。這種抽屜效果勺美,都是十分好看經(jīng)典的設(shè)計(jì)。
但是在flutter中鸦做,只有側(cè)邊抽屜励烦,沒(méi)看到有上拉的抽屜谓着。項(xiàng)目中UI需要下面的效果:

Flutter抽屜

本文更多是傳遞flutter學(xué)習(xí)與開(kāi)發(fā)自定義Widget的一個(gè)思想泼诱。能夠更好的理解Flutter的GestureRecognizer、Transform赊锚、AnimationController等等

分析

遇到一個(gè)問(wèn)題或者需求治筒,我更建議大家把需求細(xì)化,細(xì)分舷蒲。然后逐個(gè)分析耸袜,個(gè)個(gè)擊破。

  • 抽屜里存放列表數(shù)據(jù)牲平。上拉小于一定值 堤框,自動(dòng)回彈到底部
  • 當(dāng)抽屜未到達(dá)頂部時(shí),上拉列表纵柿,抽屜上移蜈抓。
  • 當(dāng)抽屜到到達(dá)頂部時(shí),上拉列表昂儒,抽屜不動(dòng)沟使,列表數(shù)據(jù)移動(dòng)。
  • 抽屜的列表數(shù)據(jù)渊跋,下拉時(shí)腊嗡,出現(xiàn)最后一條數(shù)據(jù)時(shí)着倾,整個(gè)抽屜隨之下拉
  • 抽屜上拉時(shí),有一個(gè)向上的加速度時(shí)燕少,手指離開(kāi)屏幕卡者,抽屜會(huì)自動(dòng)滾到頂部

解決方案

GestureRecognizer

母庸質(zhì)疑,這里涉及到更多的是監(jiān)聽(tīng)手勢(shì)客们。監(jiān)聽(tīng)手指按下虎眨、移動(dòng)、抬起以及加速度移動(dòng)等镶摘。這些嗽桩,通過(guò)flutter強(qiáng)大的GestureRecognizer就可以搞定。

Flutter Gestures 中簡(jiǎn)單來(lái)說(shuō)就是可以監(jiān)聽(tīng)用戶的以下手勢(shì):

  • Tap

    • onTabDown 按下
    • onTapUp 抬起
    • onTap 點(diǎn)擊
    • onTapCancel
  • Double tap 雙擊

  • Vertical drag 垂直拖動(dòng)屏幕

    • onVerticalDragStart
    • onVerticalDragUpdate
    • onVerticalDragEnd
  • Horizontal drag 水平拖動(dòng)屏幕

    • onHorizontalDragStart
    • onHorizontalDragUpdate
    • onHorizontalDragEnd
  • Pan

    • onPanStart 可能開(kāi)始水平或垂直移動(dòng)凄敢。如果設(shè)置了onHorizontalDragStart或onVerticalDragStart回調(diào)碌冶,則會(huì)導(dǎo)致崩潰 。
    • onPanUpdate 觸摸到屏幕并在垂直或水平方移動(dòng)涝缝。如果設(shè)置了onHorizontalDragUpdate或onVerticalDragUpdate回調(diào)扑庞,則會(huì)導(dǎo)致崩潰 。
    • onPanEnd 在停止接觸屏幕時(shí)以特定速度移動(dòng)拒逮。如果設(shè)置了onHorizontalDragEnd或onVerticalDragEnd回調(diào)罐氨,則會(huì)導(dǎo)致崩潰 。

每個(gè)行為滩援,均有著對(duì)應(yīng)的Recognizer去處理栅隐。

分別對(duì)應(yīng)著下面:

GestureRecognizer

在這里我們用到的就是VerticalDragGestureRecognizer,用來(lái)監(jiān)聽(tīng)控件垂直方向接收的行為。

    
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 移動(dòng)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}');
  }

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

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

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


3.gif

很簡(jiǎn)單的玩徊,我們就完成了widget跟隨手指上下移動(dòng)租悄。

使用動(dòng)畫(huà)

之前我們有說(shuō)道,當(dāng)我們松開(kāi)手時(shí)恩袱,控件會(huì)自動(dòng)跑到最下面泣棋,或者跑到最頂端。這里呢畔塔,我們就需要使用到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(() {});
      });

    ///自己滾動(dòng)
    animalController.forward();

33.gif

在手指離開(kāi)屏幕的回調(diào)方法中潭辈,在void _onEnd(DragEndDetails details)使用animalController,也就是當(dāng)手指離開(kāi)屏幕澈吨,將上層的DragContainer歸到原位把敢。

到這里,已經(jīng)解決了棚辽。滾動(dòng)技竟,自動(dòng)歸位。下一步屈藐,就是解決比較困難的情況榔组。

解決嵌套列表數(shù)據(jù)

在抽屜中熙尉,我們經(jīng)常存放的是列表數(shù)據(jù)。所以搓扯,會(huì)有下面的情況:

列表數(shù)據(jù)

也就是說(shuō)检痰,在下拉列表時(shí),只有第一條顯示后锨推,整個(gè)DragContainer才會(huì)隨之下移铅歼。但是在Flutter中,并沒(méi)有可以判斷顯示第一條數(shù)據(jù)的回調(diào)監(jiān)聽(tīng)换可。但是官方椎椰,有NotificationListener,用來(lái)進(jìn)行滑動(dòng)監(jiān)聽(tīng)的。

ScrollNotification

  • ScrollStartNotification 部件開(kāi)始滑動(dòng)
  • ScrollUpdateNotification 部件位置發(fā)生改變
  • OverscrollNotification 表示窗口小部件未更改它的滾動(dòng)位置沾鳄,因?yàn)楦臅?huì)導(dǎo)致滾動(dòng)位置超出其滾動(dòng)范圍
  • ScrollEndNotification 部件停止?jié)L動(dòng)

可以有童鞋有疑問(wèn)慨飘,為什么使用監(jiān)聽(tīng)垂直方向的手勢(shì)去移動(dòng)位置,而不用 ScrollUpdateNotification去更新DragContainer的位置译荞。這是因?yàn)椋?code>ScrollNotification這個(gè)東西是一個(gè)滑動(dòng)通知瓤的,他的通知是有延遲!
的。官方有說(shuō):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.

也就是說(shuō)吞歼,我們可以將DragContainer放在NotificationListener中圈膏,當(dāng)觸發(fā)了ScrollEndNotification的時(shí)候,也就是說(shuō)整個(gè)列表數(shù)據(jù)需要向下移動(dòng)了篙骡。


///在ios中稽坤,默認(rèn)返回BouncingScrollPhysics,對(duì)于[BouncingScrollPhysics]而言医增,
///由于   double applyBoundaryConditions(ScrollMetrics position, double value) => 0.0;
///會(huì)導(dǎo)致:當(dāng)listview的第一條目顯示時(shí)慎皱,繼續(xù)下拉時(shí),不會(huì)調(diào)用上面提到的Overscroll監(jiān)聽(tīng)叶骨。
///故這里,設(shè)定為[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] 部件開(kāi)始滑動(dòng)
  ///[ScrollUpdateNotification] 部件位置發(fā)生改變
  ///[OverscrollNotification] 表示窗口小部件未更改它的滾動(dòng)位置祈匙,因?yàn)楦臅?huì)導(dǎo)致滾動(dòng)位置超出其滾動(dòng)范圍
  ///[ScrollEndNotification] 部件停止?jié)L動(dòng)
  ///之所以不能使用這個(gè)來(lái)build或者layout忽刽,是因?yàn)檫@個(gè)通知的回調(diào)是會(huì)有延遲的。
  ///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 {
  ///滑動(dòng)開(kāi)始
  start,

  ///滑動(dòng)結(jié)束
  end,

  ///滑動(dòng)時(shí)夺欲,控件在邊緣(最上面顯示或者最下面顯示)位置
  edge
}

通過(guò)這個(gè)方案跪帝,我們就解決了列表數(shù)據(jù)的問(wèn)題。最后一個(gè)問(wèn)題些阅,當(dāng)手指快速向上滑動(dòng)的時(shí)候然后松開(kāi)手的時(shí)候伞剑,讓列表數(shù)據(jù)自動(dòng)滾動(dòng)頂端。這個(gè)快速上滑市埋,如何解決黎泣。

當(dāng)dragContainer中使用的是ScrollView恕刘,一定要將physics的值設(shè)定為ClampingScrollPhysics,否則不能監(jiān)聽(tīng)到ScrollEndNotification抒倚。這是平臺(tái)不一致性導(dǎo)致的褐着。在scroll_configuration.dart中,有這么一段:

scroll_configuration

判斷Fling

對(duì)于這個(gè)托呕,是我在由項(xiàng)目需求含蓉,魔改源碼的時(shí)候,無(wú)意中看到的项郊。所以需要翻源碼了馅扣。在DragGestureRecognizer中,官方有一個(gè)也是判斷Filing的地方着降,

_isFlingGesture

不過(guò)這個(gè)方法是私有的岂嗓,我們無(wú)法調(diào)用。(雖然dart可以反射鹊碍,但是不建議厌殉。),我們就按照官方的思路一樣的寫(xiě)就好了侈咕。


///MyVerticalDragGestureRecognizer 負(fù)責(zé)任務(wù)
///1.監(jiān)聽(tīng)child的位置更新
///2.判斷child在手松的那一刻是否是出于fling狀態(tài)
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();
  }

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

    ///VelocityEstimate 計(jì)算二維速度的
    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) 會(huì)調(diào)用[_handleDragEnd]
    ///所以將[lingListener(isFling);]放在前一步調(diào)用
    super.didStopTrackingLastPointer(pointer);
  }

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

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

最后效果

part1.gif
part2.gif

模擬器有點(diǎn)卡~

源碼地址

博客地址

Flutter 豆瓣客戶端耀销,誠(chéng)心開(kāi)源
Flutter 豆瓣客戶端楼眷,誠(chéng)心開(kāi)源
Flutter Container
Flutter SafeArea
Flutter Row Column MainAxisAlignment Expanded
Flutter Image全解析
Flutter 常用按鈕總結(jié)
Flutter ListView豆瓣電影排行榜
Flutter Card
Flutter Navigator&Router(導(dǎo)航與路由)
OverscrollNotification不起效果引起的Flutter感悟分享
Flutter 上拉抽屜實(shí)現(xiàn)

Flutter 更改狀態(tài)欄顏色

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市熊尉,隨后出現(xiàn)的幾起案子罐柳,更是在濱河造成了極大的恐慌,老刑警劉巖狰住,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件张吉,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡催植,警方通過(guò)查閱死者的電腦和手機(jī)肮蛹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)创南,“玉大人伦忠,你說(shuō)我怎么就攤上這事「逭蓿” “怎么了昆码?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我赋咽,道長(zhǎng)旧噪,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任冬耿,我火速辦了婚禮舌菜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘亦镶。我一直安慰自己日月,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布缤骨。 她就那樣靜靜地躺著爱咬,像睡著了一般。 火紅的嫁衣襯著肌膚如雪绊起。 梳的紋絲不亂的頭發(fā)上精拟,一...
    開(kāi)封第一講書(shū)人閱讀 51,718評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音虱歪,去河邊找鬼蜂绎。 笑死,一個(gè)胖子當(dāng)著我的面吹牛笋鄙,可吹牛的內(nèi)容都是我干的师枣。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼萧落,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼践美!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起找岖,我...
    開(kāi)封第一講書(shū)人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤陨倡,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后许布,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體兴革,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年爹脾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了帖旨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡灵妨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出落竹,到底是詐尸還是另有隱情泌霍,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站朱转,受9級(jí)特大地震影響蟹地,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜藤为,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一怪与、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧缅疟,春花似錦分别、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至桅咆,卻和暖如春括授,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岩饼。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工荚虚, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人籍茧。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓版述,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親硕糊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子院水,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355