Simple Example of using Draggable Widget in Flutter

By | July 2, 2023
import 'package:flutter/material.dart';

void main() {
  runApp(DraggableExample());
}

class DraggableExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Draggable Example'),
        ),
        body: Center(
          child: Draggable(
            feedback: Container(
              width: 100,
              height: 100,
              color: Colors.blue,
              child: Icon(Icons.touch_app, color: Colors.white),
            ),
            child: Container(
              width: 100,
              height: 100,
              color: Colors.blue,
              child: Icon(Icons.touch_app, color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }
}

In this example, we use the Draggable widget to create a draggable square-shaped container with a touch_app icon. Here’s a breakdown of the code:

  1. The Draggable widget is placed inside the body of a Scaffold widget.
  2. The feedback property defines the widget that will be dragged around the screen. In this example, it’s a blue container with an icon.
  3. The child property defines the original widget that remains in place while dragging. It’s also a blue container with an icon.
  4. In this simple example, we haven’t provided an onDragCompleted callback. If you need to perform an action when the dragging is completed, you can add that callback to the Draggable widget.
  5. The Draggable widget can be dragged around the screen by long-pressing and moving your finger.

You can run this code in a Flutter project to see the draggable widget in action.

Leave a Reply

Your email address will not be published. Required fields are marked *