栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Flutter TextField-如果输入的文本溢出则如何缩小字体

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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<Home> {  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: <Widget>[ 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: <Widget>[       Container(width: _textWidth, height: 20.0, color: Colors.blue),     ],   ), )          ],        ),      ),    );  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385562.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号