我尝试获取一些文本小部件。 例如,列中我的 2 个小部件是计数器小部件和文本小部件。 计数器小部件显示文本小部件的行数。 我尝试使用
TextPainter
。它可以计算文本小部件的行数,但不正确,并且当此文本小部件与同一行中的另一个小部件保持一致时,它会得到不正确的行。
我的示例代码:
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)),
],
),
],
);
},
);
}
}
您可以在dart pad上测试此代码,通过拖动屏幕尺寸来更改其屏幕尺寸。
我的示例结果:
我调整了你的布局代码
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),
]);
},
)),
],
);
_count
是正确的