我有以下文本,我想像这样处理:如果用户输入前两个数字,则用户将在此文本字段中输入数据,然后在用户输入最后两个数字之前自动插入 / 。
代码
Container(
width: MediaQuery.of(context).size.width * 0.45,
child: TextField(
style: style,
maxLength: 4,
cursorColor: Colors.red,
textAlign: TextAlign.left,
keyboardType: TextInputType.datetime,
decoration: InputDecoration(
filled: true,
fillColor: Color(0xFF1E1E1E),
hintText: 'MM/YY',
hintStyle: TextStyle(fontSize: 16, color: Colors.white),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.all(16),
),
),
),
最佳答案
InputFormatter
并在TextField
中编写用于格式化文本的逻辑。flutter_mask_text
的软件包,可减轻创建自定义InputFormatter的压力。我将链接添加到下面的包中:软件包的示例演示:
创建一个 Controller :
var controller = new MaskedTextController(mask: '00/00');
将 Controller 分配给您的TextField
: Container(
width: MediaQuery.of(context).size.width * 0.45,
child: TextField(
controller: controller, // new line
style: style,
maxLength: 4,
cursorColor: Colors.red,
textAlign: TextAlign.left,
keyboardType: TextInputType.datetime,
decoration: InputDecoration(
filled: true,
fillColor: Color(0xFF1E1E1E),
hintText: 'MM/YY',
hintStyle: TextStyle(fontSize: 16, color: Colors.white),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.all(16),
),
),
),
关于android - 如何处理Flutter中的文字栏位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569173/