Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a line Between Widgets

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

MyBoxes

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?

like image 581
Msyk Avatar asked Jul 23 '19 07:07

Msyk


1 Answers

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

Illustration

like image 147
creativecreatorormaybenot Avatar answered Sep 21 '22 07:09

creativecreatorormaybenot