I tried to get a number of the text widget.
For example, My 2 widgets in the column are the counter widget and the text widget.
The counter widget shows the number of lines of the text widget.
I tried using TextPainter. It can count lines of text widgets but not correctly and it will get incorrect lines when this text widget stays with another widget in the same row.
My example code:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: CountTextLine(
text:
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
),
),
);
}
}
class CountTextLine extends StatefulWidget {
final String text;
const CountTextLine({super.key, required this.text});
@override
State<CountTextLine> createState() => _CountTextLineState();
}
class _CountTextLineState extends State<CountTextLine> {
int _count = 0;
late final _textPainter = TextPainter(
text: TextSpan(text: widget.text),
maxLines: null,
textDirection: TextDirection.ltr,
);
@override
void initState() {
super.initState();
}
void _updateTextPainter(double width) {
_textPainter.layout(maxWidth: width);
_count = _textPainter.computeLineMetrics().length;
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
_updateTextPainter(constraints.maxWidth);
return Column(
children: [
Text(_count.toString()),
Row(
children: [
Container(
height: 200,
color: Colors.green,
child: Text('Hello My World I Am The Another Widget!!!!!'),
),
Expanded(child: Text(widget.text)),
],
),
],
);
},
);
}
}
You can test this code on dart pad by dragging the screen size to change its screen size.
My example result:

LayoutBuilder was used for the whole page. Yes, I can use the LayoutBuilder for each Text widget to use constraints.maxWidth of Text widget width to get the number of text lines but can we not use the LayoutBuilder for each Text widget that I want to count the number of text? (optional required).

I adjusted your layout code
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 200,
color: Colors.green,
child: Text('Hello My World I Am The Another Widget!!!!!'),
),
Expanded(child: LayoutBuilder(
builder: (context, constraints) {
_updateTextPainter(constraints.maxWidth);
return Column(children: [
Text(_count.toString()),
Text(widget.text),
]);
},
)),
],
);
the result looks like this

the _count is correct
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With