如何使文本垂直增长并截断?

时间:2019-04-28 14:12:12

标签: dart flutter flutter-layout

我的代码很简单:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(),
          body: Container(
              height: 60,
              color: Colors.orangeAccent,
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              )),
        ));
  }
}

它产生以下内容:

enter image description here

我想要实现的是:

enter image description here

我可以通过将maxLines: 3添加到Text来做到这一点,但是显然不能硬编码maxLines

我希望Text填充父元素的整个高度,并在需要时用省略号截断。

1 个答案:

答案 0 :(得分:1)

这是什么

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(),
      body: Container(
          height: 60,
          color: Colors.orangeAccent,
          child: Row(
            children: [
              Expanded(
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    return Text(
                      'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
                      overflow: TextOverflow.ellipsis,
                      maxLines: (constraints.maxHeight / Theme.of(context).textTheme.body1.fontSize).floor() - 1,
                    );
                  },
                ),
              ),
            ],
          )),
    ));
  }
}