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,
),
),
),
CodePudding user response:
when you define newTaskTitle
inside body, every time keyboard open and close , your widget rebuild and newTaskTitle
define again. You should define newTaskTitle
outside build method like this:
class MyWidget extends StatefulWidget {
MyWidget({Key? key}) : super(key: key);
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String newTaskTitle = '';//<---- define here
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
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,
),
),
),
]),
);
}
}