flutter - 将字段文本缩小到比提示文本更小的宽度
问题描述
我会链接到创建一个TextField
缩小到里面的文本。为此,我使用了这个说使用小部件的答案IntrinsicWidth
。它工作得很好,但是如果我指定 a hintText
,即使用户输入了非常短的文本,它的宽度TextField
也不会小于的宽度。hintText
这是一个例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
alignment: Alignment.center,
height: 50,
width: 300,
child: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
color: Colors.grey[100],
child: IntrinsicWidth(
child: TextField(
decoration: InputDecoration(
hintText: 'My very very long hint', // Remove it and the text field can be as small as the text inside
),
),
),
),
),
),
),
);
}
}
文本域的宽度就是里面文本的宽度,就是我想要的。✔️
没有文本的时候,文本域的宽度就是提示的宽度,这就是我想要的。✔️
字段的宽度就是里面文字的宽度,这就是我想要的。✔️
如您所见,字段宽度是提示的宽度,而不是里面的文本(这不是我想要的 ❌)。
如何强制它成为内部实际文本的宽度?
解决方案
hintText
您可以根据您的内容有条件地更改TextEditingController
:
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() => runApp(MyApp());
class MyApp extends HookWidget {
@override
Widget build(BuildContext context) {
final _controller = useTextEditingController();
final _editing = useState(false);
_controller.addListener(() => _editing.value = _controller.text.isNotEmpty);
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
alignment: Alignment.center,
width: 300,
child: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(10),
color: Colors.grey[100],
child: Column(
children: [
IntrinsicWidth(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(
hintText: _editing.value
? '' // empty hintText if field is not empty
: 'My very very long hint',
),
),
),
],
),
),
),
),
),
);
}
}
推荐阅读
- mysql - 从视图中选择时不能在子查询中使用参数
- c# - 我不能多次搜索“文本框”
- python - 如何使用 Anaconda (windows) 安装 Wxpython?
- kubernetes - 如何保护 Google Kubernetes Engine (GKE) 中的只读端口 10255?
- c# - httpClient 200 响应但正文为空?
- r - 由 tidygraph 计算的无向网络图显示的度中心性超出了应有的范围
- java - 上传 pdf 文件时出现 SSL 异常
- css - 如何在 :after 选择器保持在背景和正确位置后制作背景图像?
- c# - C# FluentFTP 连接错误 - FTPS Windows 7
- javascript - 用于动画的 Ext js 面板显示不起作用