在小部件之间画一条线 [英] Drawing a line Between Widgets

查看:120
本文介绍了在小部件之间画一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flutter应用程序中,我想用一条线连接两个任意框。

该示例在 GridView MyBoxes 。 c $ c>。

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

我想从MyBox滑动在左侧的MyBox右侧,并在它们之间的空间中绘制一条线以显示连接。

但是,我找不到在小部件边框之外绘制线的方法。

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.

是否可以通过诸如CustomPainter之类的绘画技巧或更改小部件的结构来做到这一点?

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

推荐答案

我认为这可能是一个不错的挑战,所以我只是使用 CustomPainter 。就个人而言,我将始终使用自定义 RenderObject 使用 LeafRenderObjectWidget RenderBox ,但是 CustomPainter 应该更容易,这就是为什么我在本示例中使用它。

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.

基本思想是使用 堆栈 ,其中既包含您的盒子,又包含 CustomPainter ,可让您超越限制任何单个小部件的。在我的示例中,我并没有弄清楚这些线,也不确保它们连接两个框,但是,您可以通过提供 GlobalKey 到您的盒子,将这些密钥存储在全局列表中(例如,在 InheritedWidget 或提供程序),然后应用 (globalKey.currentContext.findRenderObject返回的位置的某些逻辑()作为RenderBox).localToGlobal(Offset.zero) 。您也可以使用 globalKey访问框的大小.currentContext.size

但是,这对于答案来说有点太过分了,这就是为什么我只共享代码的基本上下文在两个小部件之间绘制线条:

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:

这篇关于在小部件之间画一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆