首页 > 解决方案 > 如何在 FLUTTER 中使用信用卡日期格式 mm/yy

问题描述

 child: new TextFormField(                             
   maxLength:5,                                        
   controller:                                         
       TextEditingController(text: donation.date),    
   onChanged: (value) {                                
     donation.date = value;                           
   },                                                  
   decoration: InputDecoration(                        
     suffixText: '',                                   
     suffixStyle: TextStyle(                           
       color: Color(0xffde0486),                       
     ),                                                 
     labelText: 'Expiry Date',                         
     border: OutlineInputBorder(),                     
   ),                                                   
   keyboardType: TextInputType.number,                 
   textInputAction: TextInputAction.done,              
   style: TextStyle(color: Colors.white),              
   autofocus: true,                                    
 ),                                                     


          

我有这段代码用于我在Flutter中实现的信用卡。我想将 mm/yy 格式放在文本字段上。当用户输入月份时,文本字段应自动显示“/”。我该怎么做呢?

标签: flutterdart

解决方案


您可以使用该onChange方法实现您的结果。您可以检查输入的长度,如果它是 2,则在文本中插入一个“/”,即dd

  1. 您需要将控制器存储在单独的变量中,因为我们想稍后使用它来插入“/”:
var _controller = new TextEditingController(text: donation.date);
  1. 将此_controlleronChange回调添加到您的TextFormField
TextFormField(                                     
  controller: _controller, //<-- Add controller here
   onChanged: (value) {
     if(value.length == 2) _controller.text += "/"; //<-- Automatically show a '/' after dd
     donation.date = value;                     
   },
   ...                                    
 ),     

推荐阅读