Search code examples
androidandroid-studioflutterflutter-layoutflatbutton

Value of variable altered by Text Field is not updated in Flat Button


Here is the build function. The variable newTaskTitle which is initially null takes the value from the TextField. But this value is not reflected in the Flat Button widget. The value of newTaskTitle remains null at the FlatButton widget. Help me understand where I went wrong.

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: <Widget>[
            Text(
              'Add Task',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 30,
              ),
            ),
            TextField(
              autofocus: true,
              textAlign: TextAlign.center,
              onChanged: (newText) {
                newTaskTitle = newText;
                print(newTaskTitle);
              },
            ),
            SizedBox(
              height: 10,
            ),
            FlatButton(
              padding: EdgeInsets.all(10),
              color: Colors.lightBlueAccent,
              onPressed: () {
                print(newTaskTitle);
                addTaskCallback(newTaskTitle);
              },
              child: Text(
                'Add',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

To clone the project, the partially completed code can be found here: https://github.com/vkmanojk/Flutter/tree/master/todoey_flutter

Thanks in advance.


Solution

  • Hey Manoj I can see you have used stateless widget to do this task, And you are declaring your variable here :

    Widget build(BuildContext context) {
    String newTaskTitle;     <----- Here 
    

    So My answer is dont declare it here Please declare it as in global umm like this below your import

    import 'material.dart';
    String newTaskTitle;   <--- Here or anywhere outside the scope of Stateless widget
    

    Now we usually prefer using Stateful widgets for the task like this. Hope this works : )