Drawing a line Between Widgets


Asked by Msyk on July 23, 2019 (source).

In my Flutter application, I want to connect two arbitrary boxes with a line.
The example shows two MyBoxes in a GridView.


I want to swipe from MyBox on the left to MyBox on the right and draw a line in the space between them to show the connection.
However, I couldn't find a way to draw lines beyond the widget border.

Is there a way to do this with drawing tricks like CustomPainter, or with changes to the widget's structure?


Question answered by creativecreatorormaybenot (source).

I thought that this might be a nice challenge, so I just created a minimum viable example using CustomPainter. Personally, I would always use a custom RenderObject using LeafRenderObjectWidget and RenderBox, however, CustomPainter's are supposed to be easier, which is why I will use it for this example.

The basic idea is having a Stack that contains both your boxes and the CustomPainter, which allows you to draw beyond the constraints of any single widget. In my example, I do not straighten the lines and do not ensure that they connect two boxes, however, you could easily add this by supplying GlobalKey's to your boxes, storing these keys in a global list (e.g. in an InheritedWidget or Provider) and then applying some logic to the positions returned by (globalKey.currentContext.findRenderObject() as RenderBox).localToGlobal(Offset.zero). You can also access the size of your boxes like this using globalKey.currentContext.size.
This, however, would be a bit too much for an answer, which is why I will only share code for the basic context of drawing lines between two widgets:

Source code as a Gist