繁体   English   中英

如何检测 flutter 中的滑动

[英]How to detect swipe in flutter

我已经尝试使用 flutter 的滑动检测器插件来实现向右滑动导航到新屏幕,但它不起作用,没有抛出任何错误,并且在我调试它时从未遇到断点。 我查看了 GestureDector,但我不确定它是否适用于向右滑动的场景,我们希望它在屏幕上的任何地方向右滑动时导航到屏幕。

这是我使用插件的代码

 @override
 Widget build(BuildContext context){
return new Scaffold(
 appBar : LBAppBar().getAppBar(),
  //drawer: new LBDrawer().getDrawer(),
 body:  Container(
decoration: BoxDecoration(
    gradient: new LinearGradient(
        colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
        begin: Alignment.bottomLeft,
        end: Alignment.topRight
    )
),
 child: 
 SwipeDetector(
     onSwipeRight: () {
       Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new WidgetsPage())
        ); },
  child: Column(
  mainAxisAlignment: MainAxisAlignment.center,    
  children:[
    Row(
            children: [
          Container(
            margin: EdgeInsets.only(left: 20.0,top: 10.0, bottom: 10.0, right:30.0),
            child: Column(
  children: <Widget>[



            Text("Hi ${user.firstName}, Today is " + formatDate(), style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 19.0 
 )),




        ],

         ),
                 ),
                  ]
            ),

      Row(
        //ROW 1
        children: [
          Container(
            margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
      children: <Widget>[
           GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.checkSquare,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                        Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckIn()));
                      }),
                Text("Check In", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
              ),
              Container(
           margin: EdgeInsets.only(left: 50.0,top: 60.0, bottom: 30.0, right:30.0),
                child: Column(
      children: <Widget>[
           GestureDetector(

                 child: Icon(
                 FontAwesomeIcons.list,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new DayAtAGlance()));
                      }),
            Text("My Day", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),
               ),
            Container(
           margin: EdgeInsets.only(left: 30.0,top: 60.0, bottom: 30.0, right:30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.phone,
                 size: 45.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CommunicationLinks()));
                      }),
              Text("Communication", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
 ),
             ),
             ]
              ),
         Row(//ROW 2
          children: [
        Container(
           margin: EdgeInsets.only(left: 32.0,top: 50.0, bottom: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.dollarSign,
                 size: 50.0,
                  color: Colors.white70,
           ),
              onTap: () {
                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Budget()));
                      }),
            Text("Budget", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
],
 ),

              ),
        Container(
           margin: EdgeInsets.only(left: 75.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.trophy,
                 size: 50.0,
                  color:  Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Goals", style: new TextStyle( color:  Colors.white70, fontWeight: FontWeight.normal ))
],
),

            ),
         Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.calendar,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {

                   Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CalendarsPage()));
                      }),
            Text("Calendar", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),
            )
         ]),
      Row(// ROW 3
          children: [
        Container(
           margin: EdgeInsets.only(left: 30.0, top: 50.0, bottom: 30.0, right: 30.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.comments,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    print("Pressed");
                      }),
            Text("Community", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

            ),
        Container(
           margin: EdgeInsets.only(left: 20.0, top: 50.0, bottom: 30.0, right: 20.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.shoppingCart,
                 size: 50.0,
                 color: Colors.white70,
         ),
              onTap: () {
                     Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new ShoppingList()));
                      }),
            Text("Shopping", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.normal ))
  ],
),

              ),
          Container(
           margin: EdgeInsets.only(left: 50.0, top: 50.0, bottom: 30.0, right: 40.0),
            child: Column(
  children: <Widget>[
       GestureDetector(
                 child: Icon(
                 FontAwesomeIcons.solidCheckSquare,
                 size: 50.0,
                  color: Colors.white70,
         ),
              onTap: () {
                    Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckOut()));
                      }),
            Text("Check Out", style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold ))
],
),

            ),
      ]),
    ],
      ),
   )


 )


   );

使用GestureDetector.onPanUpdate

GestureDetector(
  onPanUpdate: (details) {
    // Swiping in right direction.
    if (details.delta.dx > 0) {}
  
    // Swiping in left direction.
    if (details.delta.dx < 0) {}
  },
  child: YourWidget(),
)

要覆盖所有区域(将父约束传递给小部件),您可以包含SizedBox.expand

SizedBox.expand(
  child: GestureDetector(
    onPanUpdate: (details) {
      // Swiping in right direction.
      if (details.delta.dx > 0) {}

      // Swiping in left direction.
      if (details.delta.dx < 0) {}
    },
    child: YourWidget(),
  ),
)

将您的Widget包裹在GestureDetector并使用onHorizontalDragUpdate作为,

GestureDetector(
    onHorizontalDragUpdate: (details) {  
        // Note: Sensitivity is integer used when you don't want to mess up vertical drag
        int sensitivity = 8;
        if (details.delta.dx > sensitivity) {
            // Right Swipe
        } else if(details.delta.dx < -sensitivity){
            //Left Swipe
        }
    }
);

或者,如果您正在寻找垂直滑动,您可以使用以下代码:

GestureDetector(
    onVerticalDragUpdate: (details) {
        int sensitivity = 8;
        if (details.delta.dy > sensitivity) {
            // Down Swipe
        } else if(details.delta.dy < -sensitivity){
            // Up Swipe
        }
    }
)

背负@Vimal Rai 的回答。 我发现 onHorizo​​ntalDragUpdate 每次更新都会调用该函数。 这可能会导致您的应用出现不良行为。 如果您希望在滑动时只调用一次该函数,请使用 OnHorizo​​ntalDragEnd:

GestureDetector(
    onHorizontalDragEnd: (DragEndDetails details) {
      if (details.primaryVelocity > 0) {
        // User swiped Left
      } else if (details.primaryVelocity < 0) {
        // User swiped Right
      }
    }
);

在某些情况下,如果GestureDetector用作其他可滚动小部件的子级或父级,则它不会触发手势事件。 检测任何手势的最佳方法是使用Listener小部件。

Listener(
   onPointerMove: (moveEvent){
      if(moveEvent.delta.dx > 0) {
          print("swipe right");
      }
   }
    child: PageView(...) // or any other widget
)

对我来说,这里的其他解决方案会导致问题,例如每次滑动触发多次触发。 我最终使用了带有onHorizontalDragEnd的手势检测器,并且每次滑动只触发一次。

class MyPageView extends StatefulWidget {
  @override
  _MyPageViewState createState() => _MyPageViewState();
}

class _MyPageViewState extends State<MyPageView> {
  PageController _pageController;
  Duration pageTurnDuration = Duration(milliseconds: 500);
  Curve pageTurnCurve = Curves.ease;

  @override
  void initState() {
    super.initState();
    // The PageController allows us to instruct the PageView to change pages.
    _pageController = PageController();
  }

  void _goForward() {
    _pageController.nextPage(duration: pageTurnDuration, curve: pageTurnCurve);
  }

  void _goBack() {
    _pageController.previousPage(
        duration: pageTurnDuration, curve: pageTurnCurve);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        // Using the DragEndDetails allows us to only fire once per swipe.
        onHorizontalDragEnd: (dragEndDetails) {
          if (dragEndDetails.primaryVelocity < 0) {
            // Page forwards
            print('Move page forwards');
            _goForward();
          } else if (dragEndDetails.primaryVelocity > 0) {
            // Page backwards
            print('Move page backwards');
            _goBack();
          }
        },
        child: PageView.builder(
            itemCount: 10,
            controller: _pageController,
            // NeverScrollableScrollPhysics disables PageView built-in gestures.
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              return new Center(child: Text('item ${++index}'));
            }),
      ),
    );
  }
}

这是我使用 GestureDetector 的解决方案。 我将处理程序放在 onPanEnd 中,因为在进行滑动时会多次调用 onPanUpdate。

@override
  Widget build(BuildContext context) {
    String swipeDirection;

    return GestureDetector(
      onPanUpdate: (details) {
        swipeDirection = details.delta.dx < 0 ? 'left' : 'right';
      },
      onPanEnd: (details) {
        if (swipeDirection == 'left') {
          //handle swipe left event
        }
        if (swipeDirection == 'right') {
          //handle swipe right event
        }
      },
      child: //child widget
    );
  }

答案在源代码消失后更新

现在您可以将swipedetectorSwipeConfiguration dart 类一起使用,即检测向上、向下、向左、向右滑动。

使用 SwipeDetector 很简单,只需将它包裹在要检测滑动的 Widget 周围即可。

要使用swipedetector类,只需复制并粘贴文件代码或将以下 dart 文件拖放到项目目录中。 并作为import 'package:[Your directory path]/swipedetector.dart'

创建一个swipedetector.dart并将此代码复制并粘贴到您的文件中

import 'package:flutter/material.dart';

class SwipeConfiguration {
  //Vertical swipe configuration options
  double verticalSwipeMaxWidthThreshold = 50.0;
  double verticalSwipeMinDisplacement = 100.0;
  double verticalSwipeMinVelocity = 300.0;

  //Horizontal swipe configuration options
  double horizontalSwipeMaxHeightThreshold = 50.0;
  double horizontalSwipeMinDisplacement = 100.0;
  double horizontalSwipeMinVelocity = 300.0;

  SwipeConfiguration({
    double verticalSwipeMaxWidthThreshold,
    double verticalSwipeMinDisplacement,
    double verticalSwipeMinVelocity,
    double horizontalSwipeMaxHeightThreshold,
    double horizontalSwipeMinDisplacement,
    double horizontalSwipeMinVelocity,
  }) {
    if (verticalSwipeMaxWidthThreshold != null) {
      this.verticalSwipeMaxWidthThreshold = verticalSwipeMaxWidthThreshold;
    }

    if (verticalSwipeMinDisplacement != null) {
      this.verticalSwipeMinDisplacement = verticalSwipeMinDisplacement;
    }

    if (verticalSwipeMinVelocity != null) {
      this.verticalSwipeMinVelocity = verticalSwipeMinVelocity;
    }

    if (horizontalSwipeMaxHeightThreshold != null) {
      this.horizontalSwipeMaxHeightThreshold = horizontalSwipeMaxHeightThreshold;
    }

    if (horizontalSwipeMinDisplacement != null) {
      this.horizontalSwipeMinDisplacement = horizontalSwipeMinDisplacement;
    }

    if (horizontalSwipeMinVelocity != null) {
      this.horizontalSwipeMinVelocity = horizontalSwipeMinVelocity;
    }
  }
}

class SwipeDetector extends StatelessWidget {
  final Widget child;
  final Function() onSwipeUp;
  final Function() onSwipeDown;
  final Function() onSwipeLeft;
  final Function() onSwipeRight;
  final SwipeConfiguration swipeConfiguration;

  SwipeDetector(
      {@required this.child,
      this.onSwipeUp,
      this.onSwipeDown,
      this.onSwipeLeft,
      this.onSwipeRight,
      SwipeConfiguration swipeConfiguration})
      : this.swipeConfiguration = swipeConfiguration == null
            ? SwipeConfiguration()
            : swipeConfiguration;

  @override
  Widget build(BuildContext context) {
    //Vertical drag details
    DragStartDetails startVerticalDragDetails;
    DragUpdateDetails updateVerticalDragDetails;

    //Horizontal drag details
    DragStartDetails startHorizontalDragDetails;
    DragUpdateDetails updateHorizontalDragDetails;

    return GestureDetector(
      child: child,
      onVerticalDragStart: (dragDetails) {
        startVerticalDragDetails = dragDetails;
      },
      onVerticalDragUpdate: (dragDetails) {
        updateVerticalDragDetails = dragDetails;
      },
      onVerticalDragEnd: (endDetails) {
        double dx = updateVerticalDragDetails.globalPosition.dx -
            startVerticalDragDetails.globalPosition.dx;
        double dy = updateVerticalDragDetails.globalPosition.dy -
            startVerticalDragDetails.globalPosition.dy;
        double velocity = endDetails.primaryVelocity;

        //Convert values to be positive
        if (dx < 0) dx = -dx;
        if (dy < 0) dy = -dy;
        double positiveVelocity = velocity < 0 ? -velocity : velocity;

        if (dx > swipeConfiguration.verticalSwipeMaxWidthThreshold) return;
        if (dy < swipeConfiguration.verticalSwipeMinDisplacement) return;
        if (positiveVelocity < swipeConfiguration.verticalSwipeMinVelocity)
          return;

        if (velocity < 0) {
          //Swipe Up
          if (onSwipeUp != null) {
            onSwipeUp();
          }
        } else {
          //Swipe Down
          if (onSwipeDown != null) {
            onSwipeDown();
          }
        }
      },
      onHorizontalDragStart: (dragDetails) {
        startHorizontalDragDetails = dragDetails;
      },
      onHorizontalDragUpdate: (dragDetails) {
        updateHorizontalDragDetails = dragDetails;
      },
      onHorizontalDragEnd: (endDetails) {
        double dx = updateHorizontalDragDetails.globalPosition.dx -
            startHorizontalDragDetails.globalPosition.dx;
        double dy = updateHorizontalDragDetails.globalPosition.dy -
            startHorizontalDragDetails.globalPosition.dy;
        double velocity = endDetails.primaryVelocity;

        if (dx < 0) dx = -dx;
        if (dy < 0) dy = -dy;
        double positiveVelocity = velocity < 0 ? -velocity : velocity;

        if (dx < swipeConfiguration.horizontalSwipeMinDisplacement) return;
        if (dy > swipeConfiguration.horizontalSwipeMaxHeightThreshold) return;
        if (positiveVelocity < swipeConfiguration.horizontalSwipeMinVelocity)
          return;

        if (velocity < 0) {
          //Swipe Up
          if (onSwipeLeft != null) {
            onSwipeLeft();
          }
        } else {
          //Swipe Down
          if (onSwipeRight != null) {
            onSwipeRight();
          }
        }
      },
    );
  }
}

并像这样使用它

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SwipeDetector(
          child: Container(height: 200, width: 300), //Your Widget Tree here
          onSwipeUp: () {
            print("Swipe Up");
          },
          onSwipeDown: () {
           print("Swipe Down");
          },
          onSwipeLeft: () {
            print("Swipe Left");
          },
          onSwipeRight: () {
            print("Swipe Right");
          },
        ),
      ),
    );
  }

下载swipedetector.dart文件https://github.com/pkmangukiya/SwipeDetector/blob/main/swipedetector.dart

另一种方法是将您的小部件包装在一个可关闭的..这在我的情况下效果很好,因为它具有交互式动画,允许用户以清晰的方式中止。

 Dismissible(
        key: UniqueKey(),
        child: yourWidget, //the widget you want the swipe to be detected on
        direction: DismissDirection.up, // or whatever
        confirmDismiss: (direction) {
          if (direction == DismissDirection.up) { // or other directions
            // Swiped up do your thing.
          }
          return Future.value(false); // always deny the actual dismiss, else it will expect the widget to be removed
        })

因为我想使用滑动来浏览图库中的图片,所以我尝试了onPanUpdate的第一个答案。 然而,这在滑动期间触发了几次,这在这里是不可行的。

因此我最终使用了这段代码:

child: GestureDetector(
  onHorizontalDragEnd: (details) => controller.swipe(details),
  child: Image.file(
      controller.photos[controller.iterator.value]),
),
void swipe(DragEndDetails details) {
  if (details.primaryVelocity == null) {
    return;
  }
  if (details.primaryVelocity! < 0) {
    int next = iterator.value + 1;
    if (next >= photos.length) next = 0;
    iterator.value = next;
  }
  if (details.primaryVelocity! > 0) {
    int next = iterator.value - 1;
    if (next < 0) next = photos.length - 1;
    iterator.value = next;
  }
}

这当然可以根据问题进行调整。

尝试使用 PageView。 你可以给它一组页面,然后你可以通过向右滑动来导航。

https://api.flutter.dev/flutter/widgets/PageView-class.html

此解决方案基于平移而不是拖动。 如果您只想检测一个轴上的滑动并且不想强制执行诸如最小位移或最大横轴位移之类的限制,那么拖动会更简单并完成工作。 如果您需要更多控制或想要检测 4 个方向(水平开始但更改为垂直被检测为水平),平移是您的朋友。

此解决方案添加了 HitTestBehaviour.opaque 以允许在可点击元素上方滑动,还修复了一种情况,即在滑动的开始和结束位置用两根手指轻敲将触发滑动(不需要的行为)。

import 'package:flutter/material.dart';

class SwipeDetector extends StatelessWidget {
  static const double minMainDisplacement = 50;
  static const double maxCrossRatio = 0.75;
  static const double minVelocity = 300;

  final Widget child;

  final VoidCallback? onSwipeUp;
  final VoidCallback? onSwipeDown;
  final VoidCallback? onSwipeLeft;
  final VoidCallback? onSwipeRight;

  SwipeDetector({
    required this.child,
    this.onSwipeUp,
    this.onSwipeDown,
    this.onSwipeLeft,
    this.onSwipeRight,
  });

  @override
  Widget build(BuildContext context) {
    DragStartDetails? panStartDetails;
    DragUpdateDetails? panUpdateDetails;

    return GestureDetector(
      onTapDown: (_) => panUpdateDetails = null,  // This prevents two fingers quick taps from being detected as a swipe
      behavior: HitTestBehavior.opaque, // This allows swipe above other clickable widgets
      child: child,
      onPanStart: (startDetails) => panStartDetails = startDetails,
      onPanUpdate: (updateDetails) => panUpdateDetails = updateDetails,
      onPanEnd: (endDetails) {
        if (panStartDetails == null || panUpdateDetails == null) return;

        double dx = panUpdateDetails!.globalPosition.dx -
            panStartDetails!.globalPosition.dx;
        double dy = panUpdateDetails!.globalPosition.dy -
            panStartDetails!.globalPosition.dy;

        int panDurationMiliseconds =
            panUpdateDetails!.sourceTimeStamp!.inMilliseconds -
                panStartDetails!.sourceTimeStamp!.inMilliseconds;

        double mainDis, crossDis, mainVel;
        bool isHorizontalMainAxis = dx.abs() > dy.abs();

        if (isHorizontalMainAxis) {
          mainDis = dx.abs();
          crossDis = dy.abs();
        } else {
          mainDis = dy.abs();
          crossDis = dx.abs();
        }

        mainVel = 1000 * mainDis / panDurationMiliseconds;

        // if (mainDis < minMainDisplacement) return;
        // if (crossDis > maxCrossRatio * mainDis) return;
        // if (mainVel < minVelocity) return;

        if (mainDis < minMainDisplacement) {
          debugPrint(
              "SWIPE DEBUG | Displacement too short. Real: $mainDis - Min: $minMainDisplacement");
          return;
        }
        if (crossDis > maxCrossRatio * mainDis) {
          debugPrint(
              "SWIPE DEBUG | Cross axis displacemnt bigger than limit. Real: $crossDis - Limit: ${mainDis * maxCrossRatio}");
          return;
        }
        if (mainVel < minVelocity) {
          debugPrint(
              "SWIPE DEBUG | Swipe velocity too slow. Real: $mainVel - Min: $minVelocity");
          return;
        }

        // dy < 0 => UP -- dx > 0 => RIGHT
        if (isHorizontalMainAxis) {
          if (dx > 0)
            onSwipeRight?.call();
          else
            onSwipeLeft?.call();
        } else {
          if (dy < 0)
            onSwipeUp?.call();
          else
            onSwipeDown?.call();
        }
      },
    );
  }
}

用法

@override
Widget build(BuildContext context) {
return SwipeDetector(
      onSwipeUp:    // your on swipe ↑ handler,
      onSwipeRight: // your on swipe → handler,
      onSwipeDown:  // your on swipe ↓ handler,
      onSwipeLeft:  // your on swipe ← handler,
      child: Center... 

像这样声明变量:

Offset? _initialSwipeOffset;
Offset? _finalSwipeOffset;
SwipeDirection? _previousDirection;
SimpleSwipeConfig swipeConfig = const SimpleSwipeConfig();

在 State Class 中的构建方法下方声明所有这些方法:

1)

void _onHorizontalDragStart(DragStartDetails details) {
 _initialSwipeOffset = details.globalPosition;
}
void _onHorizontalDragUpdate(DragUpdateDetails details) {
  _finalSwipeOffset = details.globalPosition;
  if (swipeConfig.swipeDetectionBehavior == SwipeDetectionBehavior.singularOnEnd) {
     return;
  }

final initialOffset = _initialSwipeOffset;
final finalOffset = _finalSwipeOffset;

if (initialOffset != null && finalOffset != null) {
  final offsetDifference = initialOffset.dx - finalOffset.dx;

  if (offsetDifference.abs() > swipeConfig.horizontalThreshold) {
    _initialSwipeOffset = swipeConfig.swipeDetectionBehavior == SwipeDetectionBehavior.singular ? null : _finalSwipeOffset;

    final direction = offsetDifference > 0 ? SwipeDirection.left : SwipeDirection.right;

    if (swipeConfig.swipeDetectionBehavior == SwipeDetectionBehavior.continuous || _previousDirection == null || direction != _previousDirection) {
      _previousDirection = direction;
    }
  }
 }
}
void _onHorizontalDragEnd(DragEndDetails details) {
if (swipeConfig.swipeDetectionBehavior == SwipeDetectionBehavior.singularOnEnd) 
 {
  final initialOffset = _initialSwipeOffset;
  final finalOffset = _finalSwipeOffset;

  if (initialOffset != null && finalOffset != null) {
    final offsetDifference = initialOffset.dx - finalOffset.dx;

    if (offsetDifference.abs() > swipeConfig.horizontalThreshold) {
      final direction = offsetDifference > 0 ? SwipeDirection.left : SwipeDirection.right;
      if (direction == SwipeDirection.left) {
        print("Swiping to Left");
        return;
      }
      print("Swiping to Right");
    }
  }
}

 _initialSwipeOffset = null;
 _previousDirection = null;
}

在文件末尾声明滑动手势配置,如下所示:

class SimpleSwipeConfig {
  final double verticalThreshold;
  final double horizontalThreshold;
  final SwipeDetectionBehavior swipeDetectionBehavior;
  const SimpleSwipeConfig({
   this.verticalThreshold = 50.0,
   this.horizontalThreshold = 50.0,
   this.swipeDetectionBehavior = SwipeDetectionBehavior.singularOnEnd,
 });
}

简单声明最后两个枚举,如下所示:

enum SwipeDetectionBehavior {
 singular,
 singularOnEnd,
 continuous,
 continuousDistinct,

}

enum SwipeDirection { left, right, up, down }

现在,在您的 GestureDetector 中简单地调用这些函数

GestureDetector(
  onHorizontalDragStart: _onHorizontalDragStart,
  onHorizontalDragEnd: _onHorizontalDragEnd,
  onHorizontalDragUpdate: _onHorizontalDragUpdate,
  child:...
 );

注意:按原样复制并粘贴上面的代码,它将与魅力一起工作:)

您可以使用 GestureDetector class 中的onPanUpdate方法检测滑动。

GestureDetector(onPanUpdate: (details) {
  if (details.delta.dx > 0)
    print("Dragging in +X direction");
  else
    print("Dragging in -X direction");

  if (details.delta.dy > 0)
    print("Dragging in +Y direction");
  else
    print("Dragging in -Y direction");
});

我用它来上下滑动

GestureDetector(
      onVerticalDragEnd: (details) => swipe(details),
      child: ...
);
void swipe(DragEndDetails details) {
if (details.primaryVelocity == null) {
  return;
}
if (details.primaryVelocity! < 0) {
   //'up'
  setState(() {
    _value = true;
  });
}
if (details.primaryVelocity! > 0) {
 // 'down'
  setState(() {
    _value = false;
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM