Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15073

How to get BoxConstraints by using context?

I want to get the constraints by using context in a function(before build method).

In build() method, If we use LayoutBuilder at the very beginning, it provides the constraints that the child can occupy. Then is it possible to get them via context directly?

If not, then explain how LayoutBuilder provides this constraints.

Upvotes: 3

Views: 1863

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277527

No, it is not possible using only context.

Widgets are not able to:

  • obtain constraints
  • read their position
  • read their parents/siblings/...

The only reason that LayoutBuilder is able to pass a BoxConstraint to the widget tree is that it uses something that is not a widget:

RenderObject

As such, if your goal is to remove a bit of boilerplate by using context directly instead of LayoutBuilder, then forget it.

To achieve something similar to LayoutBuilder is relatively complex and verbose.

Upvotes: 4

Related Questions