Flutter Draggable example

Last updated on January 4, 2021 A Goodman Loading... Post a comment

Learn how to use the Draggable widget in Flutter through a full example.

In general, the Draggable widget goes along with the DragTarget widget:

  • Draggable: Creates a widget that can be dragged to a target.
  • DragTarget: Receives data when a dragged widget is dropped.

Below is a complete example of implementing the Draggable widget in Flutter.

Example

Our example app contains 2 boxes. The first one displays a network image and is draggable. The second one is just a color box at the beginning but it can take the dragged image then displays it.

The code:

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // the image that will be displayed in the target
  String _targetImageUrl;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              /////////////////////
              /// Draggable
              Draggable<String>(
                data:
                    "https://www.kindacode.com/wp-content/uploads/2020/11/my-dog.jpg",
                child: Container(
                  width: 300,
                  height: 200,
                  alignment: Alignment.center,
                  color: Colors.purple,
                  child: Image.network(
                    'https://www.kindacode.com/wp-content/uploads/2020/11/my-dog.jpg',
                    fit: BoxFit.cover,
                  ),
                ),
                // The widget to show under the pointer when a drag is under way
                feedback: Opacity(
                  opacity: 0.4,
                  child: Container(
                    color: Colors.purple,
                    width: 300,
                    height: 200,
                    alignment: Alignment.center,
                    child: Image.network(
                      'https://www.kindacode.com/wp-content/uploads/2020/11/my-dog.jpg',
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              SizedBox(height: 50),
              ////////////////////////
              /// Target
              DragTarget<String>(
                onAccept: (value) {
                  setState(() {
                    _targetImageUrl = value;
                  });
                },
                builder: (_, candidateData, rejectedData) {
                  return Container(
                    width: 300,
                    height: 200,
                    color: Colors.amber,
                    alignment: Alignment.center,
                    child: _targetImageUrl != null
                        ? Image.network(
                            _targetImageUrl,
                            fit: BoxFit.cover,
                          )
                        : Container(),
                  );
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

This example is quite simple but from here, you’re good to go.

API

Draggable constructor:

Draggable({
  Key key, 
  @required Widget child, 
  @required Widget feedback, 
  T data, 
  Axis axis, 
  Widget childWhenDragging, 
  Offset feedbackOffset: Offset.zero, 
  DragAnchor dragAnchor: DragAnchor.child, 
  Axis affinity, 
  int maxSimultaneousDrags, 
  VoidCallback onDragStarted, 
  DraggableCanceledCallback onDraggableCanceled,   
  DragEndCallback onDragEnd, 
  VoidCallback onDragCompleted, 
  boolignoringFeedbackSemantics: true
})

DragTarget constructor:

DragTarget({
  Key key, 
  @required DragTargetBuilder<T> builder,      
  DragTargetWillAccept<T> onWillAccept, 
  DragTargetAccept<T> onAccept, 
  DragTargetAcceptWithDetails<T> onAcceptWithDetails, 
  DragTargetLeave onLeave, 
  DragTargetMove onMove
})

You can learn more about Flutter by taking a look at these articles: Using RichText and TextSpan in FlutterWorking with Table in FlutterGuide to InteractiveViewer in FlutterFlutter FadeTransition example, or check out our Flutter category page for the latest stuff.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles