fluttergesturedetector

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


Is there a better way to check Left/Right Drag in #flutter. I have done it but somtime it works sometime it doesn't.

  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"),
  ),
);

Solution

  • I would just use a Dismissible widget for this. It's pretty configurable.

    video

    Note: If you don't want to provide visual feedback on the swipe, you could use a Stack to put a transparent Dismissible on top of another widget.

    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,
              ),
            ),
          ),
        );
      }
    }