FlatButton onPressed打印null

问题描述 投票:0回答:3

[每当我使用FlatButton onPressed方法打印变量值时,它都将返回null,我也不知道为什么。当我将变量设置为静态值textField时更改工作良好,但FlatButton打印静态值

 Widget build(BuildContext context) {

String newTaskTitle;

return Material(
  child: Container(
    color: Color(0xff757575),
    child: Container(
      padding: EdgeInsets.all(20.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.0),
          topRight: Radius.circular(20.0),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Text(
            'Add Task',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 30.0,
              color: Colors.lightBlueAccent,
            ),
          ),
          TextField(
            autofocus: true,
            textAlign: TextAlign.center,
            onChanged: (newText) {
              newTaskTitle = newText;
              // prints the equal value    

              print(newText);
            },
          ),
          FlatButton(
            child: Text(
              'Add',
              style: TextStyle(
                color: Colors.white,
              ),
            ),
            color: Colors.lightBlueAccent,
            onPressed: () {
              print(newTaskTitle);
              // Navigator.pop(context);
            },
          ),
          RaisedButton(

            onPressed: () {
              // prints null    

              print(newTaskTitle);
              // Navigator.pop(context);
            },
          )
        ],
      ),
    ),
  ),
);
}

我不知道怎么了,请帮帮我

flutter flutter-layout
3个回答
0
投票

请使您的String newTaskTitle;这个变量全局,我的意思是从build()方法中定义此变量

类似:

String newTaskTitle;

Widget build(BuildContext context) {
  /* do your work  */
}

[只要您尝试在TextField()中设置文本,然后在build()方法中调用,并且您的变量值设置为null,这就是为什么您需要定义newTaskTitle方法之外的build


-1
投票

我怀疑此行newTaskTitle = newText;不会重建您的页面。尝试将其包装在setState()内。

setState(() => newTaskTitle = newText);

-1
投票

这是因为未重建组件,所以打印的值将始终是初始值(即null),而不是您使用TextField更新的值。

您可以在TextField的onChanged()函数中或在Button小部件的onTap()中进行打印(newTaskTitle)之前使用setState()。

第一选项:

    TextField(
      onChanged: (newText) => setState(() => newTaskTitle = newText),    
    ),

第二个选项:

    RaisedButton(
      onPressed: () {
        setState(() {});
        print(newTaskTitle)
      }
    )

如果您需要将窗口小部件从无状态更改为有状态,则可以使用StatefullBuilder()而不是更改整个结构)>

© www.soinside.com 2019 - 2024. All rights reserved.