Constraining Draggable area

后端 未结 1 1484
渐次进展
渐次进展 2021-01-19 12:22

I\'m attempting to create a draggable slider-like widget (like a confirm slider). My question is if there is a way to constrain the draggable area?

import \'         


        
相关标签:
1条回答
  • 2021-01-19 13:19

    No. That's not the goal of Draggable widget. Instead, use a GestureDetector to detect drag. Then combine it with something like Align to move your content around

    Here's a fully working slider based on your current code.

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Slider(),
            ),
          ),
        );
      }
    }
    
    class Slider extends StatefulWidget {
      final ValueChanged<double> valueChanged;
    
      Slider({this.valueChanged});
    
      @override
      SliderState createState() {
        return new SliderState();
      }
    }
    
    class SliderState extends State<Slider> {
      ValueNotifier<double> valueListener = ValueNotifier(.0);
    
      @override
      void initState() {
        valueListener.addListener(notifyParent);
        super.initState();
      }
    
      void notifyParent() {
        if (widget.valueChanged != null) {
          widget.valueChanged(valueListener.value);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.green,
          height: 50.0,
          padding: EdgeInsets.symmetric(horizontal: 40.0),
          child: Builder(
            builder: (context) {
              final handle = GestureDetector(
                onHorizontalDragUpdate: (details) {
                  valueListener.value = (valueListener.value +
                          details.delta.dx / context.size.width)
                      .clamp(.0, 1.0);
                },
                child: FlutterLogo(size: 50.0),
              );
    
              return AnimatedBuilder(
                animation: valueListener,
                builder: (context, child) {
                  return Align(
                    alignment: Alignment(valueListener.value * 2 - 1, .5),
                    child: child,
                  );
                },
                child: handle,
              );
            },
          ),
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题