颤振:如何在登录表单中自动填写密码

Posted

技术标签:

【中文标题】颤振:如何在登录表单中自动填写密码【英文标题】:flutter: how to autofill password in login form 【发布时间】:2021-07-05 07:33:23 【问题描述】:

我正在尝试当用户选中复选框时,它会在用户再次登录时自动填充密码,我在密码文本字段中尝试了自动填充提示并将小部件包装在 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。 检查用户名和密码是否为空,如果为空则将用户名和密码存储在首选项中。 如果它不为 null,则将 textController 的值设置为 sharedPrefrences 中的值。

【讨论】:

我用答案编辑我的代码,请检查这是你想说的! 请邀请我聊天。 怎么做?你能告诉我这里吗

以上是关于颤振:如何在登录表单中自动填写密码的主要内容,如果未能解决你的问题,请参考以下文章

jquery 防止自动填充表单

颤振 |如何将数据添加到 Firestore 中的现有文档

怎么记住密码

如何使用 Ember 从表单中读取自动填写的用户名/密码

Greasemonkey:如何自动填写登录表单?

c#添加webBrowser控件,如何实现自动填写打开的网页中的登录帐号,密码,并且自动登陆?