flutter中一个方块,当手指按压方块向左滑动,方块跟着手向左滑动,松开手后方块一定完成100距离的向左滑动

72 阅读1分钟

flutter中一个方块,当手指按压方块向左滑动,方块跟着手向左滑动,松开手后方块一定完成100距离的向左滑动


import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _leftPosition = 100.0;
  bool _isDragging = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('滑动方块示例'),
      ),
      body: Center(
        child: GestureDetector(
          onHorizontalDragStart: (details) {
            _isDragging = true;
          },
          onHorizontalDragUpdate: (details) {
            if (_isDragging) {
              setState(() {
                _leftPosition += details.delta.dx;
              });
            }
          },
          onHorizontalDragEnd: (details) {
            _isDragging = false;
            double targetPosition = _leftPosition - 100.0;
            if (targetPosition < 0.0) {
              targetPosition = 0.0;
            }
            setState(() {
              _leftPosition = targetPosition;
            });
          },
          child: Stack(
            children: [
              Container(
                width: double.infinity,
                height: 100.0,
                color: Colors.grey,
              ),
              Positioned(
                left: _leftPosition,
                top: 0,
                child: Container(
                  width: 100.0,
                  height: 100.0,
                  color: Colors.blue,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}