'How do I access the MediaQuery in a PreferredSizeWidget getSize method?
I am write a PreferredSizeWidget implementation. My widget wraps a single Text widget. To properly calculate the required height I need to multiply the text size by the MediaQuery.textScaleFactor.
The only way to know the size of the widget is to have access to the parent MediaQuery. I do not have access to the build context inside the PreferredSizeWidget getSize method.
How can I get around this limitation of PreferredSizeWidget?
Solution 1:[1]
In short, you can't.
The preferredSize getter needs to return a fixed size. It cannot be some dynamic value determined at runtime because the property is part of the widget, not the element(state), so you won't have access to BuildContext in the getter.
See this answer for some workarounds: https://stackoverflow.com/a/62708948/1032613
If none of those workarounds suit your needs, you can consider dropping Scaffold altogether (if you don't really need a Scaffold anyway). Or, if you use other nice Scaffold things such as the "floating action button", you can consider dropping the appBar property of Scaffold, and design your own custom app bar as part of the Scaffold's body, for example, use a Column() as its body, and put your own app bar there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | WSBT |
