问题描述
我正在尝试在text
中安排两个row
。第二个文本只有几个单词,但是第一个可能很长。我的目标是完全显示第二个文本,并用第一个文本填充剩余的空间。如果第一个小部件太宽,我想用省略号将其截断。
我的代码是
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
GlobalKey key = GlobalKey();
return Row(
children: [
Container(
child: Text("Really really really long long long teeeeext",maxLines: 1,overflow: TextOverflow.ellipsis),width: MediaQuery.of(context).size.width - MediaQuery.of(key.currentContext).size.width),Text("short text",key: key)
],);
}
}
以The following assertion was thrown building MyHomePage(dirty,dependencies: [MediaQuery]): I/flutter (28083): 'package:flutter/src/widgets/media_query.dart': Failed assertion: line 810 pos 12: 'context != I/flutter (28083): null': is not true.
失败
我猜是因为Flutter引擎尚未开始呈现“短文本”小部件,所以它的大小目前未知。
任何帮助将不胜感激。
解决方法
如果您尝试启动第二个文本小部件(如Text _secondText=Text("short text")
)怎么办?因此,当您使用第一个窗口小部件时,Flutter应该已经知道其内容。您可以尝试一下。
MediaQuery.of(context).size
在构建阶段不可用。构建小部件时,尚未计算尺寸。
但是,您不需要MediaQuery.of(context).size
来实现布局。相反,您可以简单地用Expanded
包裹左文本。然后,它将占用所有剩余空间(总宽度减去右边的文本宽度)。
Row(
children: [
Expanded(
child: Text(
"Really really really long long long teeeeext 123 123 123 123 123 123 123 123",maxLines: 1,overflow: TextOverflow.ellipsis,),Text(
"short text",],)
结果: