【发布时间】:2020-11-01 18:22:17
【问题描述】:
这里是构建函数。最初为 null 的变量 newTaskTitle 从 TextField 中获取值。但是这个值不会反映在 Flat Button 小部件中。 newTaskTitle 的值在 FlatButton 小部件中保持为空。帮助我了解我哪里出错了。
Widget build(BuildContext context) {
String newTaskTitle;
return Container(
color: Color(0xFF757575),
child: Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.lightBlueAccent,
fontSize: 30,
),
),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
print(newTaskTitle);
},
),
SizedBox(
height: 10,
),
FlatButton(
padding: EdgeInsets.all(10),
color: Colors.lightBlueAccent,
onPressed: () {
print(newTaskTitle);
addTaskCallback(newTaskTitle);
},
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
],
),
),
);
}
要克隆项目,部分完成的代码可以在这里找到:https://github.com/vkmanojk/Flutter/tree/master/todoey_flutter
提前致谢。
【问题讨论】:
-
你有没有尝试在
build()方法之外声明,并在onChanged()中调用setState() -
@MohamedSayed 我试过了。结果还是一样。另外,我使用了
StateLess小部件,因此在方法之外声明变量会引发警告并且setState()是不可能的。 -
您是否收到您在控制台中输入的字词?那是你使用 print 的时候吗?
-
@KrishBhanushali 是的。
-
当输入文本为 hhh -
I/flutter (32727): h I/flutter (32727): hh I/flutter (32727): hhh I/flutter (32727): null为控制台输出
标签: android android-studio flutter flutter-layout flatbutton