Drawing a line Between Widgets

前端 未结 1 1008
灰色年华
灰色年华 2021-01-05 12:56

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

I want

相关标签:
1条回答
  • 2021-01-05 13:31

    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

    0 讨论(0)
提交回复
热议问题