Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article introduces a super secret Flutter project I designed for the desktop and Web using a canvas and draggable node interface. This tutorial will show how I can use stack to use widgets for draggable functionality

As shown below.

We’ll dynamically add items to the stack and distinguish them, and I’ll use a RandomColor typeizer. So we have to add that package.

random_color:
Copy the code

Then we can create a HomeView that contains our stack

class HomeView extends StatefulWidget { @override _HomeViewState createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { List<Widget> movableItems = []; @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: movableItems, )); }}Copy the code

The function is very simple. We’re going to have a MoveableStackItem stateful widget. It tracks its position and color. The colors are set at initialization and the locations are updated by the GestureDetector.

class _MoveableStackItemState extends State<MoveableStackItem> { double xPosition = 0; double yPosition = 0; Color color; @override void initState() { color = RandomColor().randomColor(); super.initState(); } @override Widget build(BuildContext context) { return Positioned( top: yPosition, left: xPosition, child: GestureDetector( onPanUpdate: (tapInfo) { setState(() { xPosition += tapInfo.delta.dx; yPosition += tapInfo.delta.dy; }); }, child: Container( width: 150, height: 150, color: color, ), ), ); }}Copy the code

The last thing to do is add a new one to the MoveableStackItem view. We’ll do this via a floating action button in HomeView.

 return Scaffold(
  floatingActionButton: FloatingActionButton(
    onPressed: () {
      setState(() {
        movableItems.add(MoveableStackItem());
      });
    },
  ),
  body: Stack(
    children: movableItems,
  ));
Copy the code

That’s it. You now have a removable stack item on your view.