'How to get height of widget(container) before rendering it on screen in Flutter?

I am having one Listview which contains chat array list. Each chat item may contain single line text, multiline text and image. I need to put each chat item within Align widget with heightFactor value and heightFactor value should depend on height of chat item widget as per requirement.

Now, to calculate heightFactor value I need to have height of each chat item widget before rendering it on screen.

So how can I get height of each chat item widget before rendering it on screen?

Example: I can get total number of lines of text with styles without rendering it on screen using below code

int getNumberOfLines(String text) {
  if (text.isEmpty) return 0;

  TextStyle textStyle = GoogleFonts.roboto(
    fontSize: SizeConfig.getTextSize(16),
    fontWeight: FontWeight.w300,
    color: colorWhiteWithOpacity87,
    height: SizeConfig.getHeight(1.3),
  );

  final span = TextSpan(text: text, style: textStyle);
  final tp = TextPainter(text: span, textDirection: ui.TextDirection.ltr);
  tp.layout(maxWidth: SizeConfig.getWidth(262));
  return tp.computeLineMetrics().length;
}

likewise is there any way to get height of widget(container) before or without rendering it on screen?

Here, code of Listview builder

            ListView.builder(
              physics: BouncingScrollPhysics(),
              itemCount: _chatList.length,
              itemBuilder: (context, index) {

                double heightFactor = 1; // NEED TO CALCULATE BASED ON HEIGHT OF CHAT ITEM WIDGET

                return Align(
                  heightFactor: heightFactor,
                  child: ChatTile(
                      index: index,
                      chatModel: _chatList[index],
                    ),
                );
              },
            )


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source