Drawing a line Between Widgets

孤者浪人 提交于 2020-06-12 15:37:22

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/57159085/drawing-a-line-between-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!