如何检查Flutter Text小部件是否溢出

6ovsh4lw  于 2022-11-17  发布在  Flutter
关注(0)|答案(4)|浏览(256)

我有一个文本小部件,如果超过一定大小,它可能会被截断:

ConstrainedBox(
  constraints: BoxConstraints(maxHeight: 50.0),
  child: Text(
    widget.review,
    overflow: TextOverflow.ellipsis,
  )
);

或最大行数:

RichText(
  maxLines: 2,
  overflow: TextOverflow.ellipsis,
  text: TextSpan(
    style: TextStyle(color: Colors.black),
    text: widget.review,
  ));

我的目标是只有在发生溢出的情况下才能扩展文本。有没有合适的方法来检查文本是否溢出?
我所尝试的
我发现在RichText中,有一个RenderParagraph renderObject,它有一个私有属性TextPainter _textPainter,它有一个bool didExceedMaxLines
简而言之,我只需要访问richText.renderObject._textPainter.didExceedMaxLines,但正如您所看到的,它是私有的,带有下划线。

j8ag8udp

j8ag8udp1#

我找到了一个方法来做到这一点。完整的代码如下,但简而言之:
1.使用LayoutBuilder确定我们有多少空间。
1.使用TextPainter模拟空间内文本的呈现。
以下是完整的演示应用程序:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Text Overflow Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text("DEMO")),
        body: TextOverflowDemo(),
      ),
    );
  }
}

class TextOverflowDemo extends StatefulWidget {
  @override
  _EditorState createState() => _EditorState();
}

class _EditorState extends State<TextOverflowDemo> {
  var controller = TextEditingController();

  @override
  void initState() {
    controller.addListener(() {
      setState(() {
        mytext = controller.text;
      });
    });
    controller.text = "This is a long overflowing text!!!";
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  String mytext = "";

  @override
  Widget build(BuildContext context) {
    int maxLines = 1;
    double fontSize = 30.0;

    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: Column(
        children: <Widget>[
          LayoutBuilder(builder: (context, size) {
            // Build the textspan
            var span = TextSpan(
              text: mytext,
              style: TextStyle(fontSize: fontSize),
            );

            // Use a textpainter to determine if it will exceed max lines
            var tp = TextPainter(
              maxLines: maxLines,
              textAlign: TextAlign.left,
              textDirection: TextDirection.ltr,
              text: span,
            );

            // trigger it to layout
            tp.layout(maxWidth: size.maxWidth);

            // whether the text overflowed or not
            var exceeded = tp.didExceedMaxLines;

            return Column(children: <Widget>[
              Text.rich(
                span,
                overflow: TextOverflow.ellipsis,
                maxLines: maxLines,
              ),
              Text(exceeded ? "Overflowed!" : "Not overflowed yet.")
            ]);
          }),
          TextField(
            controller: controller,
          ),
        ],
      ),
    );
  }
}
9o685dep

9o685dep2#

有一个更短的方法可以得到文本是否溢出的答案。

bool hasTextOverflow(
  String text, 
  TextStyle style, 
  {double minWidth = 0, 
       double maxWidth = double.infinity, 
       int maxLines = 2
  }) {
  final TextPainter textPainter = TextPainter(
    text: TextSpan(text: text, style: style),
    maxLines: maxLines,
    textDirection: TextDirection.ltr,
  )..layout(minWidth: minWidth, maxWidth: maxWidth);
  return textPainter.didExceedMaxLines;
}
46scxncf

46scxncf3#

你可以在pub.dev上使用flutter插件auto_size_text。当文本溢出时,你可以设置一些小部件出现。

int maxLines = 3;
String caption = 'Your caption is here';
return AutoSizeText(
    caption,
    maxLines: maxLines,
    style: TextStyle(fontSize: 20),
    minFontSize: 15,
    overflowReplacement: Column( // This widget will be replaced. 
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(
        caption,
        maxLines: maxLines,
        overflow: TextOverflow.ellipsis,
      ),
      Text(
        "Show more",
        style: TextStyle(color: PrimaryColor.kGrey),
      )
    ],
  ),
);
eiee3dmh

eiee3dmh4#

我制作了自己的小部件,我跨项目使用它,它在构造函数中取Text小部件并读取它的属性。

import 'package:flutter/material.dart';

class OverflowDetectorText extends StatelessWidget {
  final Text child;

  OverflowDetectorText({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var tp = TextPainter(
      maxLines: child.maxLines,
      textAlign: child.textAlign ?? TextAlign.start,
      textDirection: child.textDirection ?? TextDirection.ltr,
      text: child.textSpan ?? TextSpan(
        text: child.data,
        style: child.style,
      ),
    );

    return LayoutBuilder(
      builder: (context, constrains) {
        tp.layout(maxWidth: constrains.maxWidth);
        final overflowed = tp.didExceedMaxLines;
        if (overflowed) {
          //You can wrap your Text `child` with anything
        }
        return child;
      },
    );
  }
}

相关问题