Flutter - 事件监听

2021-12-31  本文已影响0人  水煮杰尼龟
原始指针事件(Pointer Events)
 Listener buildListener() {
    return Listener(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
        ),
        onPointerDown: (event){
          HJLog('手指按下:$event', StackTrace.current);
        },
        onPointerMove: (event){
          HJLog('手指移动:$event', StackTrace.current);
        },
        onPointerUp: (event){
          HJLog('手指抬起:$event', StackTrace.current);
        },
      );
  }
}
手势识别(Gesture Detector)
点击:
双击:
长按:
纵向拖拽:
横线拖拽:
移动:
栗子
GestureDetector buildGestureDetector() {
    return GestureDetector(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
        ),
        onTap: (){
          HJLog('点击', StackTrace.current);
        },
        onTapDown: (details){
          HJLog('按下', StackTrace.current);
        },
        onTapUp: (details){
          HJLog('抬起', StackTrace.current);
        },
        onDoubleTap: (){
          HJLog('双击', StackTrace.current);
        },
      );
  }
  
  /// 嵌套手势
  GestureDetector buildDoubleGestureDetector() {
    return GestureDetector(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.orange,
          alignment: Alignment.center,
          child: GestureDetector(
            child: Container(
              width: 100,
              height: 100,
              color: Colors.red,
            ),
            onTapDown: (_){
              HJLog('red tapDown', StackTrace.current);
            },
          ),
        ),
        onTapDown: (_){
          HJLog('orange tapDown', StackTrace.current);
        },
      );
  }
  /// 忽略事件响应
  IgnorePointer(
              child: GestureDetector(
                child: Container(
                  width: 100,
                  height: 100,
                  color: Colors.red,
                ),
                onTapDown: (_){
                  HJLog('red tapDown', StackTrace.current);
                },
              ),
            )
跨组件事件
dependencies:
  event_bus:^2.0.0
栗子
/// 创建全局的eventbus
final eventBus = EventBus();

/// 发出事件
CupertinoButton(
        child: Text('点击'),
        onPressed: (){
          // eventBus.fire('helloworld');
          UserInfo user = UserInfo('张三', 18, 180);
          eventBus.fire(user);
          }
    )
    
    
 /// 响应时间
    @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventBus.on<UserInfo>().listen((event) {
      print('${event.name} -- ${event.age} -- ${event.height}');
      setState(() {
        _msg = '${event.name} -- ${event.age} -- ${event.height}';
      });
    });
  }
上一篇下一篇

猜你喜欢

热点阅读