【发布时间】:2021-10-15 19:21:04
【问题描述】:
我有以下小部件。
import 'package:flutter/material.dart';
class AddTaskScreen extends StatelessWidget {
@override
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: [
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30,
color: Colors.lightBlueAccent,
),
),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (String newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
// this line prints null
// even though I typed something in my textfield
print(newTaskTitle);
},
)
],
),
),
);
}
}
在这里,我使用变量 newTaskTitle 更新我的文本字段值。当文本值更改时,它会成功更新。但是当我单击添加按钮时,它会将 newTaskTitle 打印为 null。我什至在文本字段的 onChanged 中打印它,它正在获取更新的值。但它没有在添加按钮的 onPressed 函数中获取更新的值。我如何获得更新的值,我在这里做错了什么?
【问题讨论】:
-
您提供的代码为我打印文本...
-
我可以确认提供的代码正如@esentis所说的那样完美运行
标签: flutter dart dart-null-safety flutter-state