首页 > 解决方案 > 如何在不调用 setState 方法的情况下禁用按钮?

问题描述

嗨,我想在用户输入少于 10 位的手机号码时禁用凸起的按钮。用户输入 10 位数的手机号码后,它将被启用,但如果号码小于 10 位数,它将再次被禁用。目前我正在借助 set state 方法来做到这一点。但我不认为这是可行的,因为 build 函数被一次又一次地调用。这是我的代码。

TextFormField(
                    onChanged: (val){
                      number='+91' + val;
                      if(number.length==13){

                        setState(() {
                          numberlessthanten=false;
                        });
                      }
                         else{

                        setState(() {
                          numberlessthanten=true;
                        });

                      }
                    },

child: RaisedButton(

                        color: Colors.redAccent,
                        onPressed: numberlessthanten ? null : (){
                          print(number);
                          _sumbit();

                        },

                            child: Text('Send Code'),
                      ),

标签: flutter

解决方案


在您的 textformfield 中使用控制器。 TextFormField( controller = _controller ) 现在在您的凸起按钮中。

RaisedButton(
 onPressed: _controller.length <10?null:(){}
  child:Text("send Code")
 )

推荐阅读