I have a Text widget that sometimes can be fully displayed, sometimes not, depending on the widgets around.
If there is not enough space to fully display the widget, I want the widget to not show at all, I don't want it to show partially like with the overflow attribute.
If you know a way to do this, thanks.
CodePudding user response:
I don't know why you need to do this but i thing overflow
is good enough for most case, you can also use Fittedbox
to scale the text with the box with no redundant space.
In case you still want do it, you need to find the RenderBox
of that specific widget, which will contain its global position and rendered size from BuildContext
. But BuildContext
can be not exist if the widget is not rendered yet.
CodePudding user response:
If by "fully displayed" you mean that, for example, you have a SingleChildScrollView
and only half of your Text
widget is visible, you can try out this library :
https://pub.dev/packages/visibility_detector.
You can retrieve the visible percentage of your widget with the method visibilityInfo.visibleFraction
.
CodePudding user response:
LayoutBuilder
to the rescue for you!
Builds a widget tree that can depend on the parent widget's size.
Try this! Play around with the allowedTextHeightInPixels
value to see how it works.
/// Breakpoint or condition to WHEN should we display the Text widget
const allowedTextHeightInPixels = 150.0;
/// Test height for the [Text] widget.
const givenTextHeightByScreenPercentage = 0.3;
class ResponsiveTextWidget extends StatelessWidget {
const ResponsiveTextWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
print('Text height in pixels: ${constraints.maxHeight * givenTextHeightByScreenPercentage}');
return Column(
children: [
Container(
color: Colors.red,
height: constraints.maxHeight * 0.5,
),
if (constraints.maxHeight * givenTextHeightByScreenPercentage > allowedTextHeightInPixels)
const SizedBox(
child: Text(
'Responsive Me',
style: TextStyle(fontSize: 15.0),
),
),
Container(
color: Colors.blue,
height: constraints.maxHeight * 0.2,
),
],
);
},
),
),
);
}
}