flutter:如何在登录表单中自动填充密码



我正在尝试当用户选中复选框时,它将在用户再次登录时自动填充密码,我尝试在密码文本字段中自动填充提示并将小部件包装在AutofillGroup中,但它不起作用,当我登录一次并再次登录时,我需要再次输入密码。

我使用api获取用户名和密码。

这是我的登录代码

class Login extends StatefulWidget {
Login({Key key, this.title}) : super(key: key);

final String title;
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
var name,password,token;
bool _passwordVisibilty;
void initState(){
_passwordVisibilty=false;
_formatDateTime();
}
String formattedDate;
String _formatDateTime() {
var now = new DateTime.now();
var formatter = new DateFormat('yyyy-MM-dd');
formattedDate = formatter.format(now);
print(formattedDate); 


}

//svar localhostUrl="http://10.0.2.2:8000/login";
var herokuUrl="https://attendance-demo.herokuapp.com/login";
bool isSameuser = true;
final String username='';
final String email='';
final String designation='';
Future login() async {
try{
Dio dio=new Dio();
var data={
'username': user.username,
'password': user.password,
'date':formattedDate
};
await dio
.post(localhostUrlLogin,data: json.encode(data))
.then((onResponse) async {
//edited code here 
SharedPreferences myPrefs=await SharedPreferences.getInstance();

String name=(onResponse.data['User']['username']);
String password=(onResponse.data['User']['password']);
if(name==""&&password==""){
myPrefs.setString('username', name);
myPrefs.setString('password', password);
}
else{
user.username=name;
user.password=password;
}


});}catch(e){

print("error "+e.toString());


showAlertDialog(BuildContext context) {  
// Create button  
Widget okButton = FlatButton(  
child: Text("OK"),  
onPressed: () {  
Navigator.of(context).pop(); 
},  
);  

// Create AlertDialog  
AlertDialog alert = AlertDialog(  
title: Text("Error",style: TextStyle(fontWeight: FontWeight.bold)),  
content: Text("Invalid name or password.",style: TextStyle(fontSize: 17),),  
actions: [  
okButton,  
],  
);  

// show the dialog  
showDialog(  
context: context,  
builder: (BuildContext context) {  
return alert;  
},  
);  
}
User user = User('', '');
//--------------------------
passwordtext(){
return TextFieldContainer(
child: TextFormField(
controller: TextEditingController(text: user.password),
autofillHints: [AutofillHints.password],   //here is used autfodillhints
onEditingComplete: ()=>TextInput.finishAutofillContext(),  //and i used this too
decoration: InputDecoration(   
border: InputBorder.none, 
icon: Icon(Icons.lock,color: Colors.blue,),           
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_passwordVisibilty = !_passwordVisibilty;
});
},
child: Icon(
_passwordVisibilty ? Icons.visibility : Icons.visibility_off,
),
),
labelText: 'Password'),
obscureText: !_passwordVisibilty,
onChanged: (value){
user.password=value;
},
),
);
}


return Scaffold(
body: SingleChildScrollView(
child: AutofillGroup(
child: Center(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 155.0,
width: 200.0,
child: Image.asset(
"assets/image/company_logo.png",
fit: BoxFit.contain,
),
),        
SizedBox(height: 50.0),
RoundedInputField(
labelText: "Username",icon: Icons.email,fontsize: textFontSize,
controller: TextEditingController(text: user.username),
onChanged: (value){
user.username=value;
}, 

),
SizedBox(height: 15.0),
passwordtext(),
SizedBox(
height: 0.0,
),
Align(
alignment: Alignment.centerLeft,
child:Row(children: <Widget>[

Checkbox(  
checkColor: Colors.greenAccent,  
activeColor: Colors.blue, 
value: isSameuser,  
onChanged: (bool newValue) {  
if(newValue!=null){
setState(() {  
isSameuser = newValue;  
});  
}},   
),
Text("Save password?")
],)
),

SizedBox(
height: 23.0,
),
FlatButton(
color: Colors.blue[500],
textColor: Colors.white,
padding: EdgeInsets.all(15.0),                             
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(buttonRoundRadius)),
child: Row(
children:<Widget>[                   
Expanded(child: 
Text("Login",
textAlign: TextAlign.center,
style: TextStyle(fontSize: textFontSize),),)

,]),
onPressed: () {   
login();              
}               
)
]),
),
),
),
))
);
}
}

试试这个:

  1. 使用SharedPrefrences
  2. 检查用户名和密码是否为null,如果为null,则将用户名和密码存储在首选项中
  3. 如果不为null,则将textController的值设置为sharedPrefrences中的值

最新更新