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

Lia*_*ian 7 dart flutter

我有一个Text小部件,如果它超过一定的大小,可以截断:

ConstrainedBox(
  constraints: BoxConstraints(maxHeight: 50.0),
  child: Text(
    widget.review,
    overflow: TextOverflow.ellipsis,
  )
);
Run Code Online (Sandbox Code Playgroud)

或最大行数:

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

我的目标是只有在溢出完成后才能扩展文本.有没有正确的方法来检查文本是否溢出?

我试过的

我发现在RichText中有一个RenderParagraph renderObject,它有一个私有属性TextPainter _textPainter,有一个bool didExceedMaxLines.

简而言之,我只需要访问,richText.renderObject._textPainter.didExceedMaxLines但正如您所看到的,它是使用下划线私有的.

Lia*_*ian 11

我找到了一种方法。完整的代码如下,但总之:

  1. 使用LayoutBuilder确定我们有多少空间。
  2. 使用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,
          ),
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Pan*_*ara 9

您可以auto_size_textpub.dev使用 flutter 插件。当文本溢出时,您可以设置一些小部件出现。

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),
      )
    ],
  ),
);
Run Code Online (Sandbox Code Playgroud)


Val*_*ova 6

如果文本溢出与否,有一种更短的方法可以得到答案。你只需要定义 textStyle 并从这个方法中得到答案

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;
}
Run Code Online (Sandbox Code Playgroud)