flutter开发实战-手势Gesture与ListView滚动竞技场的可滑动关闭组件

flutter开发实战-手势Gesture与ListView滚动竞技场的可滑动关闭组件

最近看到了一个插件,实现一个可滑动关闭组件。滑动关闭组件即手指向下滑动,组件随手指移动,当移动一定位置时候,手指抬起后组件滑出屏幕。

一、GestureDetector嵌套Container非ListView

如果要可滑动关闭,则需要手势GestureDetector,GestureDetector这里实现了onVerticalDragDown、onVerticalDragUpdate、onVerticalDragEnd,通过手势,更新AnimatedContainer的高度。

@override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        GestureDetector(
          onVerticalDragDown: _onVerticalDragDown,
          onVerticalDragUpdate: _onVerticalDragUpdate,
          onVerticalDragEnd: _onVerticalDragEnd,
          child: AnimatedContainer(
            curve: Curves.easeOut,
            duration: Duration(milliseconds: 250),
            onEnd: () {
              _onAniPositionedEnd(context);
            },
            height: yBottomOffset + widget.displayHeight,
            width: screenSize.width,
            clipBehavior: Clip.hardEdge,
            decoration: const BoxDecoration(
              color: Colors.transparent,
            ),
            child: widget.child,
          ),
        ),
      ],
    );
  }
    

我们通过onVerticalDragUpdate来更新AnimatedContainer的高度height,

void _onVerticalDragUpdate(DragUpdateDetails details) {
    print("_onVerticalDragUpdate");
    if (details.delta.dy <= 0) {
      // 向上
      isDragDirectionUp = true;
    } else {
      // 向下
      isDragDirectionUp = false;
    }
    yBottomOffset -= details.delta.dy;
    if (yBottomOffset > 0.0) {
      yBottomOffset = 0.0;
    }

    if (yBottomOffset < -widget.displayHeight) {
      yBottomOffset = -widget.displayHeight;
    }
    setState(() {});
  }
    

当拖动手势结束之后,来检测是否是隐藏状态。

void _onVerticalDragEnd(DragEndDetails details) {
    print("_onVerticalDragEnd");
    if (yBottomOffset < -widget.displayHeight / 3) {
      // 隐藏移除
      yBottomOffset = -widget.displayHeight;
      isCompleteHide = true;
    } else {
      yBottomOffset = 0.0;
      isCompleteHide = false;
    }
    setState(() {

    });
  }
    

AnimatedContainer中有onEnd方法回调,当动画结束之后,在此方法回调中来处理是否pop等操作

void _onAniPositionedEnd(BuildContext context) {
    print("_onAniPositionedEnd");
    if (isCompleteHide) {
      // 隐藏了,则移除
      Navigator.of(context).pop();
    }
  }
    

DragBottomSheet2完整代码如下

import 'package:flutter/material.dart';

class DragBottomSheet2 extends StatefulWidget {
  const DragBottomSheet2({
    super.key,
    required this.child,
    required this.displayHeight,
  });

  // child
  final Widget child;

  // 展示的child高度
  final double displayHeight;

  @override
  State<DragBottomSheet2> createState() => _DragBottomSheet2State();
}

class _DragBottomSheet2State extends State<DragBottomSheet2> {
  bool? isDragDirectionUp;
  double yBottomOffset = 0.0;
  bool isCompleteHide = false;

  void _onVerticalDragDown(DragDownDetails details) {
    print("_onVerticalDragDown");
  }

  void _onVerticalDragUpdate(DragUpdateDetails details) {
    print("_onVerticalDragUpdate");
    if (details.delta.dy <= 0) {
      // 向上
      isDragDirectionUp = true;
    } else {
      // 向下
      isDragDirectionUp = false;
    }
    yBottomOffset -= details.delta.dy;
    if (yBottomOffset > 0.0) {
      yBottomOffset = 0.0;
    }

    if (yBottomOffset < -widget.displayHeight) {
      yBottomOffset = -widget.displayHeight;
    }
    setState(() {});
  }

  void _onVerticalDragEnd(DragEndDetails details) {
    print("_onVerticalDragEnd");
    if (yBottomOffset < -widget.displayHeight / 3) {
      // 隐藏移除
      yBottomOffset = -widget.displayHeight;
      isCompleteHide = true;
    } else {
      yBottomOffset = 0.0;
      isCompleteHide = false;
    }
    setState(() {});
  }

  void _onAniPositionedEnd(BuildContext context) {
    print("_onAniPositionedEnd");
    if (isCompleteHide) {
      // 隐藏了,则移除
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        GestureDetector(
          onVerticalDragDown: _onVerticalDragDown,
          onVerticalDragUpdate: _onVerticalDragUpdate,
          onVerticalDragEnd: _onVerticalDragEnd,
          child: AnimatedContainer(
            curve: Curves.easeOut,
            duration: Duration(milliseconds: 250),
            onEnd: () {
              _onAniPositionedEnd(context);
            },
            height: yBottomOffset + widget.displayHeight,
            width: screenSize.width,
            clipBehavior: Clip.hardEdge,
            decoration: const BoxDecoration(
              color: Colors.transparent,
            ),
            child: widget.child,
          ),
        ),
      ],
    );
  }
}

    

点击按钮弹出bottomSheet2代码如下

void showBottomSheet2(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    double displayHeight = size.height - 88;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return DragBottomSheet2(
          displayHeight: displayHeight,
          child: Container(
            width: size.width,
            height: displayHeight,
            color: Colors.orangeAccent,
            child: Text(
              '内容',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
          ),
        );
      },
    );
  }
    

效果图如下

在这里插入图片描述

二、GestureDetector嵌套ListView

GestureDetector嵌套ListView后,Flutter会根据竞技场Arena机制,通过一定逻辑选择一个组件胜出。
Flutter为了解决手势冲突问题,Flutter给开发者提供了一套解决方案。在该方案中,Flutter引入了Arena(竞技场)概念,然后把冲突的手势加入到Arena中并竞争,谁胜利,谁就获得手势的后续处理权。

Arena竞技场的原理请看https://juejin.cn/post/6874570159768633357

所以在GestureDetector嵌套ListView后,Flutter框架会将这些Gesture与ListView组件都加入竞技场,然后通过一定的逻辑选择一个组件胜出,通常同类组件嵌套时最内层的组件胜出,胜出的组件会处理接下来的move和up事件,其它组件则不会继续处理这些事件了。所以在GestureDetector嵌套ListView的场景中,由于是ListView最终胜出,所以后续的事件都交由ListView处理,而GestureDetector收不到后续的事件,也就不会响应用户的手势了。因此,我们解决这个问题的第一步就是要让GestureDetector在这种场景下也能收到后续的事件

参考请看https://zhuanlan.zhihu.com/p/680586251

我们需要根据GestureDetector真正处理用户手势事件的是内部的Recognizer,比如处理上下滑动的是VerticalDragGestureRecognizer而Recognizer在竞技场失败后也可以单方面宣布自己胜出这样即使在竞技场失败了,GestureDetector也能收到后续的手势事件
因此我们现定义一个单方面宣布胜出的Recognizer

class _MyVerticalDragGestureRecognizer extends VerticalDragGestureRecognizer {
  @override
  void rejectGesture(int pointer) {
    // 单方面宣布自己胜出
    acceptGesture(pointer);
  }
}
    

我们需要将Recognizer加入到GestureDetector中,会用到RawGestureDetector

RawGestureDetector(
      gestures: {
        _MyVerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<
                _MyVerticalDragGestureRecognizer>(
            () => _MyVerticalDragGestureRecognizer(),
            (_MyVerticalDragGestureRecognizer recognizer) {
          recognizer
            ..onStart = (DragStartDetails details) {
              
            }
            ..onUpdate = (DragUpdateDetails details) {
              
            }
            ..onEnd = (DragEndDetails details) {
             
            };
        }),
      },
      child: ...
    );
    

这时候当滚动ListView时候,也能收到手势事件了。

监听ListView的滚动,时候我们需要用到NotificationListener

 NotificationListener(  // 监听内部ListView的滑动变化
              onNotification: (ScrollNotification notification) {
                if (notification is OverscrollNotification && notification.overscroll < 0) {
                  // 用户向下滑动,ListView已经滑动到顶部,处理GestureDetector的滑动事件
                } else if (notification is ScrollUpdateNotification) {
                  // 用户在ListView中执行滑动动作,关闭外部GestureDetector的滑动处理
                } else {
                  
                }

                return false;
              },
              child:  //ListView
            ),
    

最后DragGestureBottomSheet完整代码如下

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

class DragGestureBottomSheet extends StatefulWidget {
  const DragGestureBottomSheet({
    super.key,
    required this.child,
    required this.displayHeight,
    this.duration = const Duration(milliseconds: 200),
    this.openDraggable = true,
    this.autoNavigatorPop = true,
    this.onShow,
    this.onHide,
  });

  // child
  final Widget child;

  // 展示的child高度
  final double displayHeight;

  // 拖动动画时长duration
  final Duration duration;

  // 是否需要拖动
  final bool openDraggable;

  // 是否需要自动pop
  final bool autoNavigatorPop;

  // This method will be executed when the solid bottom sheet is completely
  // opened.
  final void Function()? onShow;

  // This method will be executed when the solid bottom sheet is completely
  // closed.
  final void Function()? onHide;

  @override
  State<DragGestureBottomSheet> createState() => _DragGestureBottomSheetState();
}

class _DragGestureBottomSheetState extends State<DragGestureBottomSheet> {
  bool? isDragDirectionUp;
  double yBottomOffset = 0.0;
  bool isDraggable = false;
  bool isCompleteHide = false;

  DragSheetController? dragSheetController;

  @override
  void initState() {
    // TODO: implement initState
    dragSheetController = DragSheetController();
    dragSheetController?.dispatch(widget.displayHeight);
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    dragSheetController?.dispose();
    super.dispose();
  }

  void _onVerticalDragUpdate(data) {
    if (widget.openDraggable) {
      print("data.delta.dy:${data.delta.dy}");
      if (data.delta.dy <= 0) {
        // 向上
        isDragDirectionUp = true;
      } else {
        // 向下
        isDragDirectionUp = false;
      }
      yBottomOffset -= data.delta.dy;
      if (yBottomOffset > 0.0) {
        yBottomOffset = 0.0;
      }

      if (yBottomOffset < -widget.displayHeight) {
        yBottomOffset = -widget.displayHeight;
      }

      double height = widget.displayHeight + yBottomOffset;
      dragSheetController?.dispatch(height);
    }

  }

  void _onVerticalDragEnd(data) {
    if (widget.openDraggable) {
      // 根据判断是否隐藏与显示
      if (false == isDragDirectionUp) {
        if (yBottomOffset < -widget.displayHeight / 3) {
          // 隐藏移除
          yBottomOffset = -widget.displayHeight;
          isCompleteHide = true;
        } else {
          yBottomOffset = 0.0;
          isCompleteHide = false;
        }
      } else {
        yBottomOffset = 0.0;
        isCompleteHide = false;
      }

      double height = widget.displayHeight + yBottomOffset;
      dragSheetController?.dispatch(height);
    }
  }

  void _onAniPositionedEnd(BuildContext context) {
    // 动画结束
    print("_onAniPositionedEnd");
    if (isCompleteHide) {
      // 隐藏,则调用hiden
      if (widget.onHide != null) {
        widget.onHide!.call();
      }
    } else {
      // 显示,则调用show
      if (widget.onShow != null) {
        widget.onShow!.call();
      }
    }

    if (isCompleteHide && widget.autoNavigatorPop) {
      // 隐藏了,则移除
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        RawGestureDetector(
          gestures: {
            _MyVerticalDragGestureRecognizer:
                GestureRecognizerFactoryWithHandlers<
                        _MyVerticalDragGestureRecognizer>(
                    () => _MyVerticalDragGestureRecognizer(),
                    (_MyVerticalDragGestureRecognizer recognizer) {
              recognizer
                ..onStart = (DragStartDetails details) {}
                ..onUpdate = (DragUpdateDetails details) {
                  if (!isDraggable) {
                    return;
                  }
                  _onVerticalDragUpdate(details);
                }
                ..onEnd = (DragEndDetails details) {
                  _onVerticalDragEnd(details);
                };
            }),
          },
          child: StreamBuilder(
            stream: dragSheetController?.streamData,
            initialData: widget.displayHeight,
            builder: (_, snapshot) {
              return AnimatedContainer(
                curve: Curves.easeOut,
                duration: widget.duration,
                onEnd: () {
                  _onAniPositionedEnd(context);
                },
                height: snapshot.data,
                width: screenSize.width,
                clipBehavior: Clip.hardEdge,
                decoration: const BoxDecoration(
                  color: Colors.transparent,
                ),
                child: NotificationListener(
                  // 监听内部ListView的滑动变化
                  onNotification: (ScrollNotification notification) {
                    if (notification is OverscrollNotification &&
                        notification.overscroll < 0) {
                      // 用户向下滑动,ListView已经滑动到顶部,处理GestureDetector的滑动事件
                      isDraggable = true;
                    } else if (notification is ScrollUpdateNotification) {
                      // 用户在ListView中执行滑动动作,关闭外部GestureDetector的滑动处理
                      isDraggable = false;
                    } else {}

                    return false;
                  },
                  child: widget.child,
                ),
              );
            },
          ),
        )
      ],
    );
  }
}

class _MyVerticalDragGestureRecognizer extends VerticalDragGestureRecognizer {
  @override
  void rejectGesture(int pointer) {
    // 单方面宣布自己胜出
    acceptGesture(pointer);
  }
}

三、DragSheetController处理数据流

这里定义了DragSheetController来处理数据流,DragSheetController中包括streamController、subscription、streamSink、streamData

StreamBuilder是一个Widget,它依赖Stream来做异步数据获取刷新widget。
Stream是一种用于异步处理数据流的机制,它允许我们从一端发射一个事件,从另外一端去监听事件的变化.Stream类似于JavaScript中的Promise、Swift中的Future或Java中的RxJava,它们都是用来处理异步事件和数据的。Stream是一个抽象接口,我们可以通过StreamController接口可以方便使用Stream。

使用详情请查看https://brucegwo.blog.csdn.net/article/details/136232000

最后DragSheetController代码如下

import 'dart:async';

/// 处理Stream、StreamController相关逻辑
class DragSheetController  {
  StreamSubscription<double>? subscription;

  //创建StreamController
  StreamController<double>? streamController = StreamController<double>.broadcast();

  // 获取StreamSink用于发射事件
  StreamSink<double>? get streamSink => streamController?.sink;

  // 获取Stream用于监听
  Stream<double>? get streamData => streamController?.stream;

  // Adds new values to streams
  void dispatch(double value) {
    streamSink?.add(value);
  }

  // Closes streams
  void dispose() {
    streamSink?.close();
  }
}
    

通过DragSheetController,当拖动时候高度发生变化时候会调用dispatch方法,dispatch来发射数据流,DragGestureBottomSheet中通过StreamBuilder来调整AnimatedContainer的高度。

最后调用使用DragGestureBottomSheet

我们使用showModalBottomSheet展示DragGestureBottomSheet时候

// 显示底部弹窗
  void showCustomBottomSheet(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    double displayHeight = size.height - 88;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return DragGestureBottomSheet(
          displayHeight: displayHeight,
          autoNavigatorPop: true,
          openDraggable: true,
          onHide: () {
            print("onHide");
          },
          onShow: () {
            print("onShow");
          },
          child: Container(
            width: size.width,
            height: displayHeight,
            color: Colors.white,
            child: ScrollConfiguration(
              behavior: NoIndicatorScrollBehavior(),
              child: ListView.builder(
                itemCount: 20,
                physics: ClampingScrollPhysics(),
                itemBuilder: (context, index) {
                  return GestureDetector(
                    child: Container(
                      width: size.width,
                      height: 100,
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        border: Border.all(
                          color: Colors.black12,
                          width: 0.25,
                          style: BorderStyle.solid,
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text('index -- $index'),
                          SizedBox(
                            width: 50,
                            child: ClipOval(
                                child:
                                    Image.asset("assets/images/hero_test.png")),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      Navigator.of(context).push(
                          CupertinoPageRoute(builder: (BuildContext context) {
                        return HeroPage();
                      }));
                    },
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
    

效果图如下

在这里插入图片描述

https://brucegwo.blog.csdn.net/article/details/136241765

四、小结

flutter开发实战-手势Gesture与ListView滚动竞技场的可滑动关闭组件

学习记录,每天不停进步。

  • 12
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter提供了一个名为`BottomSheet`的小部件,用于在页面底部显示一个可滚动的内容面板。以下是一个简单的示例,演示如何使用`BottomSheet`小部件: ```dart void _showBottomSheet(BuildContext context) { showModalBottomSheet( context: context, builder: (BuildContext context) { return Container( height: 200, color: Colors.grey[200], child: Center( child: Text( 'This is a bottom sheet', style: TextStyle(fontSize: 24), ), ), ); }, ); } ``` 在上面的示例中,我们使用`showModalBottomSheet`方法显示一个带有文本的容器。您可以根据需要自定义容器的内容和样式。 您还可以使用`BottomSheet`小部件自定义底部面板并将其附加到页面的底部。以下是一个示例: ```dart void _showBottomSheet(BuildContext context) { showModalBottomSheet( context: context, builder: (BuildContext context) { return BottomSheet( onClosing: () {}, builder: (BuildContext context) { return Container( height: 200, color: Colors.grey[200], child: Center( child: Text( 'This is a custom bottom sheet', style: TextStyle(fontSize: 24), ), ), ); }, ); }, ); } ``` 在上面的示例中,我们使用`BottomSheet`小部件创建一个带有文本的容器,并将其附加到页面的底部。`onClosing`回调可用于在用户关闭底部面板时执行操作。您可以根据需要自定义容器的内容和样式。 需要注意的是,`showModalBottomSheet`方法返回一个`Future`对象,该对象在底部面板被关闭时解析。可以使用`Navigator.pop`方法从底部面板中返回数据。例如: ```dart void _showBottomSheet(BuildContext context) async { var result = await showModalBottomSheet( context: context, builder: (BuildContext context) { return Container( height: 200, color: Colors.grey[200], child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Select an option', style: TextStyle(fontSize: 24), ), SizedBox(height: 16), ElevatedButton( onPressed: () => Navigator.of(context).pop('Option 1'), child: Text('Option 1'), ), ElevatedButton( onPressed: () => Navigator.of(context).pop('Option 2'), child: Text('Option 2'), ), ], ), ), ); }, ); print(result); } ``` 在上面的示例中,我们在底部面板中显示两个按钮,并使用`Navigator.pop`方法将选定的选项返回给调用方。返回的选项将解析为`result`变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值