flutter 文字过长超出范围_Flutter TextField-如果输入的文本溢出则如何缩小字体

小编典典

使用a TextPainter来计算文本的宽度。使用a GlobalKey获取小部件的大小(使用A

LayoutBuilder可能更好地处理屏幕旋转)。

import 'package:flutter/material.dart';

main() => runApp(MaterialApp(home: Home()));

class Home extends StatefulWidget {

@override

_HomeState createState() => _HomeState();

}

const textFieldPadding = EdgeInsets.all(8.0);

const textFieldTextStyle = TextStyle(fontSize: 30.0);

class _HomeState extends State {

final TextEditingController _controller = TextEditingController();

final GlobalKey _textFieldKey = GlobalKey();

double _textWidth = 0.0;

double _fontSize = textFieldTextStyle.fontSize;

@override

void initState() {

super.initState();

_controller.addListener(_onTextChanged);

}

void _onTextChanged() {

// substract text field padding to get available space

final inputWidth = _textFieldKey.currentContext.size.width - textFieldPadding.horizontal;

// calculate width of text using text painter

final textPainter = TextPainter(

textDirection: TextDirection.ltr,

text: TextSpan(

text: _controller.text,

style: textFieldTextStyle,

),

);

textPainter.layout();

var textWidth = textPainter.width;

var fontSize = textFieldTextStyle.fontSize;

// not really efficient and doesn't find the perfect size, but you got all you need!

while (textWidth > inputWidth && fontSize > 1.0) {

fontSize -= 0.5;

textPainter.text = TextSpan(

text: _controller.text,

style: textFieldTextStyle.copyWith(fontSize: fontSize),

);

textPainter.layout();

textWidth = textPainter.width;

}

setState(() {

_textWidth = textPainter.width;

_fontSize = fontSize;

});

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Autosize TextField'),

),

body: Padding(

padding: EdgeInsets.all(16.0),

child: Column(

crossAxisAlignment: CrossAxisAlignment.stretch,

children: [

TextField(

key: _textFieldKey,

controller: _controller,

decoration: InputDecoration(

border: InputBorder.none,

fillColor: Colors.orange,

filled: true,

contentPadding: textFieldPadding,

),

style: textFieldTextStyle.copyWith(fontSize: _fontSize),

),

Text('Text width:'),

Container(

padding: textFieldPadding,

color: Colors.orange,

child: Row(

children: [

Container(width: _textWidth, height: 20.0, color: Colors.blue),

],

),

)

],

),

),

);

}

}

2020-08-13

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值