有没有更好的方法来检查 Left/Right 拖动 #flutter?

Is there a better way to check Left/Right Drag in #flutter?

是否有更好的方法来检查Left/Right拖入#flutter。我已经做到了,但有时它会起作用,有时却不起作用。

  new GestureDetector(
  onHorizontalDragEnd: (DragEndDetails details) {
      print("Drag Left - AddValue");

    setState((){
      _value++;
    });
    if (details.velocity.pixelsPerSecond.dx > -1000.0) {
      print("Drag Right - SubValue");

      setState((){
        _value--;
      });
    }
  },
  child: new Container(
    child:new Text("$_value"),
  ),
);

我会为此使用 Dismissible 小部件。它非常可配置。

注意:如果您不想在滑动时提供视觉反馈,您可以使用 Stack 将透明 Dismissible 放在另一个小部件的顶部。

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Dismissible(
        resizeDuration: null,
        onDismissed: (DismissDirection direction) {
          setState(() {
            _counter += direction == DismissDirection.endToStart ? 1 : -1;
          });
        },
        key: new ValueKey(_counter),
        child: new Center(
          child: new Text(
            '$_counter',
            style: Theme.of(context).textTheme.display4,
          ),
        ),
      ),
    );
  }
}

使用 GestureDetector 小部件及其 panUpdate 方法,计算移动的距离。

    GestureDetector(
     onPanStart: (DragStartDetails details) {
      initial = details.globalPosition.dx;
     },
     onPanUpdate: (DragUpdateDetails details) {
      distance= details.globalPosition.dx - initial;  
     },
     onPanEnd: (DragEndDetails details) {
      initial = 0.0; 
     print(distance);
     //+ve distance signifies a drag from left to right(start to end)
     //-ve distance signifies a drag from right to left(end to start)
});

使用TabBarView() 创建一个 TabController 指定 TabBarView children 中小部件的长度。

您可以使用 onHorizontalDragUpdate:

onHorizontalDragUpdate: (details){
    print(details.primaryDelta);
},

如果details.primaryDelta为正,则拖动是从左到右。 如果 details.primaryDelta 为负数,则从右到左拖动

由于详细信息是一个 DragUdate class 实例 returns double ,你可以这样做。(而且 Paageroute 默认提供这个)


GestureDetector(
       onHorizontalDragUpdate: (details) {
        if(details.primaryDelta! > 1.0) {
           Navigator.pop(context);
                      }
          },
      child:Scaffold(..)

primaryVelocity on onHorizo​​ntalDragEnd 工作正常,只需检查是否大于或小于零。

GestureDetector(
  onHorizontalDragEnd: (DragEndDetails drag) {
    if(drag.primaryVelocity == null) return;
    if(drag.primaryVelocity! < 0) {
      // drag from right to left
    }else{
      // drag from left to right
    }
  }
);