I have the following widget.
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);
},
)
],
),
),
);
}
}
Here I am updating my textfield value with the variable newTaskTitle. It successfully updates when the text value changes. But when I click on the add button, it prints the newTaskTitle as null. I even print it inside the onChanged of textfield, and it was getting the updated value. But it is not getting the updated value inside the onPressed function of the add button. How do I get the updated value and what am I doing wrong here?