我們?cè)贏PP中經(jīng)秤詹常可以看到各種抽屜,比如:某音的評(píng)論以及經(jīng)典的豆瓣評(píng)論谈况。這種抽屜效果勺美,都是十分好看經(jīng)典的設(shè)計(jì)。
但是在flutter中鸦做,只有側(cè)邊抽屜励烦,沒(méi)看到有上拉的抽屜谓着。項(xiàng)目中UI需要下面的效果:
本文更多是傳遞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)著下面:
在這里我們用到的就是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);
}
很簡(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();
在手指離開(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ì)有下面的情況:
也就是說(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)的。
-
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
中,有這么一段:
判斷Fling
對(duì)于這個(gè)托呕,是我在由項(xiàng)目需求含蓉,魔改源碼的時(shí)候,無(wú)意中看到的项郊。所以需要翻源碼了馅扣。在DragGestureRecognizer
中,官方有一個(gè)也是判斷Filing的地方着降,
不過(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的判斷。
最后效果
模擬器有點(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)