Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable FloatingActionButton in Flutter

Tags:

flutter

dart

I want to make a draggable floating button and if possible to print the drag position in the console.

like image 333
said bendrioue Avatar asked Mar 07 '19 14:03

said bendrioue


2 Answers

Due to the ability to compose Flutter widgets in whatever way you want to, you can simply do it like this:

Draggable(
    feedback: FloatingActionButton(child: Icon(Icons.drag_handle), onPressed: () {}),
    child: FloatingActionButton(child: Icon(Icons.drag_handle), onPressed: () {}),
    childWhenDragging: Container(),
    onDragEnd: (details) => print(details.offset))

This Draggable can be passed as the floatingActionButton argument to a Scaffold.
The feedback parameter controls how the widget that is dragged about in the end will look like and child specifies how the stationary Draggable should look like. As you probably only want to see one FloatingActionButton at a time, you can pass an empty Container to childWhenDragging.

The Offset (position) of the drag will be printed to the console when releasing the drag.

like image 156
creativecreatorormaybenot Avatar answered Oct 09 '22 16:10

creativecreatorormaybenot


I needed to add a positioned widget to set the position of my button

class _MyHomePageState extends State<MyHomePage> {
  Offset position =Offset(20.0, 20.0);
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: Stack(
      children: <Widget>[
        Container(
          decoration: new BoxDecoration(
            image: new DecorationImage(
              image: new AssetImage("data_repo/img/bg1.jpg"),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Positioned(
          left : position.dx,
          top  : position.dy ,
          child : Draggable(
          feedback: Container(
            child : FloatingActionButton(child: Icon(Icons.add), onPressed: () {})
            ),
          child: Container(
            child : FloatingActionButton(child: Icon(Icons.add), onPressed: () {}),
          ),
          childWhenDragging: Container(),
          onDragEnd: (details){
            setState(() {
              position = details.offset;
            });
            print(position);
            print(position.dx);
            print(position.dy);
            }))
      ],
    ));
  }
}
like image 25
said bendrioue Avatar answered Oct 09 '22 14:10

said bendrioue