Move container to a different location on touch in flutter

This Article is posted by seven.srikanth at 1/2/2023 5:21:27 AM



To move a container to a different location on touch, you can use the Positioned widget in combination with the GestureDetector widget. 
Here is the sample output of this app.
Here's the code of how you can do this:

import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @ override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Move Container on Touch App'),
        ),
        body: const TouchMoveExample(),
      ),
    );
  }
}
class TouchMoveExample extends StatefulWidget {
  const TouchMoveExample({super.key});
  @ override
  State<TouchMoveExample> createState() => _TouchMoveExampleState();
}
class _TouchMoveExampleState extends State<TouchMoveExample> {
  double _xPosition = 0;
  double _yPosition = 0;
  @ override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          left: _xPosition,
          top: _yPosition,
          child: GestureDetector(
            onPanUpdate: (details) {
              setState(() {
                _xPosition += details.delta.dx;
                _yPosition += details.delta.dy;
              });
            },
            child: Container(
              width: 100,
              height: 100,
              color: Colors.red,
            ),
          ),
        ),
      ],
    );
  }
}
Thanks,
Srikanth

Tags: drag and drop; move on touch;








0 Comments
Login to comment.
Recent Comments












© 2018 - Fluttercentral | Email to me - seven.srikanth@gmail.com