【问题标题】:I need to press the button 2 times in order to function (flutter)我需要按两次按钮才能正常工作(颤动)
【发布时间】:2020-12-06 17:00:39
【问题描述】:

我在实现登录按钮时遇到问题,当我按下它时,它一开始不起作用,但当我再次按下它时(相同的值字段)它可以工作。

这是我的代码 按钮:

 Center(child: RaisedButton(onPressed: (){
                              setState(()  {
                                onPressedLogin(userName.text,password.text);
                              });
                            }

OnPressedLogin():

void onPressedLogin(String userName,String password) async{
bool isValid = false;
var value = await dataBaseHelper.getUserList();
for(User userOB in value){
  //print(userOB.password+" "+password),
  if(userName == userOB.username && password == userOB.password) {
    isValid = true;
    this.password.clear();
    this.userName.clear();
    inputTextColor = Colors.grey[850];
    invalidCredentials = "";
    print("YES");
    //Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
    break;
  }
}
if(!isValid){
  inputTextColor = Colors.red[800];
  invalidCredentials = "Invalid Credentials";
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您正在使用 Future,但在 setState() 中您并没有等待它,所以它在第二次按下时就可以工作(值需要时间来改变)。

    要使其单次按下即可工作,您必须等待 Future 完成,然后再重建,方法如下:

    先改变函数的返回类型

    Future<void> onPressedLogin(String userName,String password)
    

    然后在RaisedButton

    onPressed: () async {
      await onPressedLogin(userName.text,password.text);
      setState(() {});
    },
    

    【讨论】:

      【解决方案2】:

      你 setState() 的那一刻,UI 会刷新! 可能就是这个问题,让我解释一下:

      你应该做的是在 setState() 之前调用你的函数,这样屏幕就会被新信息刷新。

      Center(child: RaisedButton(onPressed: (){
                                   onPressedLogin(userName.text,password.text);
                                setState(()  {
                                  //Variables that change for the refresh.
                         
                                });
                              }
      

      在您的具体情况下,我认为不需要 SetState(),因为您只是在日志中打印值,而不是更改 UI。

      希望对你有帮助。

      【讨论】:

      • 我正在更改 OnPressedLogin() 上的 UI
      • 然后,我这样做:假设您在代码的开头有 String logged = "False";您的 onPressedLogin 应该/可以为 counter logged = onPressed.. 返回一个新值。然后,刷新 UI setState(){ } 查看此链接:我认为您不完全理解 SetState stackoverflow.com/questions/51283077/…Good Luck
      • 是的,这是我第一次使用颤振(1 1/2 周)顺便说一句,由于上面的答案,我确实弄明白了,我的功能是未来,所以是的,将异步放在 onPressed 上:( ) 异步完成工作
      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 2022-08-19
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2012-09-11
      • 1970-01-01
      相关资源
      最近更新 更多