【问题标题】:Limit amount of characters of Text widget?限制文本小部件的字符数?
【发布时间】:2019-12-19 07:21:30
【问题描述】:

我正在尝试找出如何限制在颤动文本小部件中显示省略号之前显示的字符数量。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这对我来说没有一点意义,我的意思是如果你想限制文本字符的数量,那么“省略号”根本没有任何意义,所以只需将你的文本限制在一个恒定的长度

    final text = 'hello stack overflow';
    Text(text.length > 3 ? '${text.substring(0, 3)}...' : text);
    

    【讨论】:

    • 这对我有用,我正在寻找一种方法,小部件可能有一个内置设置来限制最大长度。
    【解决方案2】:

    这是一个不同的问题,但我假设您不知道如何获取文本小部件的大小,这是获取该大小的方法:How to get Widget size

    根据如何计算文本何时溢出边界,获取小部件的大小并将其分配给 widget_width 并继续使用以下伪代码,如下所示:

    double widget_width = computeWidgetWidthAsShownInLinkAbove(context, text_widget);
    
    String    sample = "This text is probably to long to fit";
    
    TextStyle textstyle  = new TextStyle(fontSize: i);
    
    int answer = 0;
    
    for ( int I = 0; I < sample.length ; I = I + 1 ) {
      TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr);
    
      textPainter.text = new TextSpan(
              text: sample.substring(0, I ), style: textstyle);
    
      textPainter.layout();
    
      if ( textPainter.width > widget_width ) {
        answer=I-1;  
        break;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2013-07-29
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多