onChanged在尝试从textField flutter分配值时返回null



我试图分配一个值,该值由用户从textField中键入,但返回null。请注意,我使用的是statelesWidget以下是我试图分配值的变量:

字符串?newTaskTitle;

这是我的代码:

class AddTaskScreen extends StatelessWidget {
const AddTaskScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
String? newTaskTitle;
return Container(
color: Colors.black,
child: Container(
padding: const EdgeInsets.all(20),
decoration: const BoxDecoration(
color: Color(0xff1f1f1f),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Add a task',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 20),
),
TextField(
cursorColor: Colors.white38,
decoration: const InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white38),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white38),
),
),
textAlign: TextAlign.center,
autofocus: true,
onChanged: (newText) {
newText = newTaskTitle!;
},
),
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateColor.resolveWith(
(states) => Colors.white.withOpacity(0.9)),
overlayColor:
MaterialStateColor.resolveWith((states) => Colors.white),
),
onPressed: () {
if (newTaskTitle == null) {
Navigator.pop(context);
print('null');
} else {
Provider.of<TaskData>(context).addTask(newTaskTitle!);
Navigator.pop(context);
}
},
child: const Text(
'Add',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
],
),
),
);
}
}

翻转赋值:

newText = newTaskTitle!;

变为:

newTaskTitle! = newText;

您分配的newText错误。

这个

String? newTaskTitle;
onChanged: (newText) {
newText = newTaskTitle!;
},

应该是这个吗

String? newTaskTitle;
onChanged: (newText) {
newTaskTitle = newText;
},

最新更新