Flutter IntrinsicHeight and IntrinsicWidth
In Flutter, IntrinsicHeight
and IntrinsicWidth
are widgets that allow their child widgets to determine their own height or width respectively based on their intrinsic dimensions.
The intrinsic dimensions of a widget are the minimum height and width required by the widget to render its content without overflowing. For example, the intrinsic height of a Text
widget is the height required to display the text without any overflow.
When an IntrinsicHeight
widget is used as a parent of its child, it sets its height to the maximum intrinsic height of its child. This can be useful in situations where you want to make sure that multiple widgets within a column have the same height.
Similarly, an IntrinsicWidth
widget sets its width to the maximum intrinsic width of its child. This can be useful in situations where you want to make sure that multiple widgets within a row have the same width.
It’s worth noting that using IntrinsicHeight
or IntrinsicWidth
can sometimes lead to performance issues, as it requires measuring the intrinsic dimensions of the child widgets. Therefore, it's recommended to use them judiciously and only when necessary.
Example :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('IntrinsicWidth and IntrinsicHeight Example')),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: Colors.blue,
width: 100,
child: Text('Box 1'),
),
Container(
color: Colors.green,
width: 150,
child: Text('Box 2\nwith\nmultiple\nlines'),
),
Container(
color: Colors.orange,
width: 75,
child: Text('Box 3'),
),
],
),
),
SizedBox(height: 20),
IntrinsicWidth(
child: Column(
children: [
Container(
color: Colors.purple,
child: Text('This is a really long text that should wrap to multiple lines'),
),
Container(
color: Colors.red,
child: Text('Short text'),
),
],
),
),
],
),
),
);
}
}
In this example, we create a Column
with two children. The first child is a Row
wrapped inside an IntrinsicHeight
widget. The Row
has three Container
widgets with different widths and heights. The IntrinsicHeight
widget ensures that all the Container
widgets have the same height based on their intrinsic heights.
The second child of the Column
is a Column
wrapped inside an IntrinsicWidth
widget. The Column
has two Container
widgets with different widths and heights. The IntrinsicWidth
widget ensures that all the Container
widgets have the same width based on their intrinsic widths.
When you run this app, you’ll see that the IntrinsicHeight
widget makes all the Container
widgets in the Row
have the same height, and the IntrinsicWidth
widget makes all the Container
widgets in the second Column
have the same width.
Thanks.