首页 > 解决方案 > 无法从 onchange 更新字符串变量

问题描述

我对颤动很陌生,我试图将 String newTask更新为文本字段中的值,但它一直将其重置为 null。

class AddTask extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String newTask;
    return Container(
      color: Color(0xff757575),
      child: Container(
        padding: EdgeInsets.symmetric(vertical:20.0,horizontal: 40.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(topLeft: Radius.circular(20.0),topRight: Radius.circular(20.0)),
        ),
        child: Column(
          children: <Widget>[
            Text('Add Task',style: TextStyle(fontSize: 30.0,color: Colors.lightBlueAccent,fontWeight: FontWeight.bold),),
            TextField(
              onChanged:(value){
                newTask = value;                
              },
              autofocus: true,),
            FlatButton(
              child: Text('Add Task'),
              onPressed: (){
                print(newTask);
              },
            ),
          ],
        ),
      ),
    );
  }
}

我究竟做错了什么?

标签: flutter

解决方案


please use below in onChanged event of TextField..

 TextField(
          onChanged:(value){
            newTask = value;                
          },
          autofocus: true,),

according to me this is correct I also run this code and its return right value.


推荐阅读