I have to use call back to raise the variable value, but while I am trying to test that if my variable gets initialized of not using a print statement, it returns null which means the variable is not initialized. //Here is my code: note that I have a variable in the body of my context which is:
String ? newTaskTitle;
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) {
newTaskTitle = newText;
},
),
FlatButton(
color: Colors.white,
onPressed: () {
print(newTaskTitle);
},
child: const Text('Add',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
when you define
newTaskTitle
inside body, every time keyboard open and close , your widget rebuild andnewTaskTitle
define again. You should definenewTaskTitle
outside build method like this: