FlatButton's onPressed prints null for a variable whose value was set from TextField's onChange function

Viewed 1698

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);
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
4 Answers

I think you should try moving the String newTaskTitle; from the build function and then make it a static property. So it becomes static String newTaskTitle;

I had the exact same problem. I just changed AddTaskScreen class to a statefull widget and moved the newTaskTitle variable outside the build method instead of declaring it inside the build method and it worked. Hope It helps somebody.

I would suspect that this line newTaskTitle = newText; does not rebuild your page. Try to make it as a page's state by bringing it outside the build function.

String newTaskTitle;

@override
void build(BuildContext context) {
  ...

Try wrapping it inside setState().

setState(() => newTaskTitle = newText);

This is because the component is not re-built, so the printed value will always be the initial one (ie null) and not the one you update with the TextField.

You can re-built your Build method only in Statefull component. You can make one of the or changing the entire structure, or using the StatefullBuilder()

First you have to change the position of your variable:

String newTaskTitle;

Widget build(BuildContext context) {
 ...
}

Second, you have to use setstate() and, in this case, you have two options:

First Option:

    TextField(
      onChanged: (newText) => setState(() => newTaskTitle = newText),    
    ),

Second Option:

    RaisedButton(
      onPressed: () {
        setState(() {});
        print(newTaskTitle)
      }
    )
Related