When value changes in the TextField, I try to capture the change, print it and then assign it to the newTaskTitle variable. I can capture and print the change to console only from the TextField's onChange function. But when I assign the value to newTaskTitle, it seems to work fine until I try to print it's value to console from the FlatButton's onPress function which results to null. It appears as if the value was never assigned from the TextField's onChange function at the first place.
The problem only goes away if newTaskTitle variable is moved up above the class definition.
What is the reason for this?
The code is shown below.
import 'package:flutter/material.dart';
class AddTaskScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
String newTaskTitle;
return Material(
child: Container(
color: Color(0xff757575),
child: Container(
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30.0,
color: Colors.lightBlueAccent,
),
),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
// prints the equal value
print(newText);
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
print(newTaskTitle);
// Navigator.pop(context);
},
),
RaisedButton(
onPressed: () {
// prints null
print(newTaskTitle);
// Navigator.pop(context);
},
)
],
),
),
),
);
}
}