I am trying to assign a value which is typed in by the user from a textField, but it returns null. Note that I am using a statelessWidget Here is the variable that I am trying to assign the value:
String? newTaskTitle;
Here is my code:
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,
),
),
),
],
),
),
);
}
}
CodePudding user response:
Turn the assignment:
newText = newTaskTitle!;
becomes to this:
newTaskTitle! = newText;
CodePudding user response:
You are assigning the newText
wrong.
This
String? newTaskTitle;
onChanged: (newText) {
newText = newTaskTitle!;
},
should be this
String? newTaskTitle;
onChanged: (newText) {
newTaskTitle = newText;
},