flutterdartdart-null-safetystatelesswidget

Flutter - The non-nullable local variable 'newTaskTitle' must be assigned before it can be used


Hi so I have been getting this error - "The non-nullable local variable 'newTaskTitle' must be assigned before it can be used. (Documentation) Try giving it an initializer expression, or ensure that it's assigned on every execution path." while building my flutter app. I am learning from Angela Yu's udemy course.

class AddTaskScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    late String newTaskTitle;
    return Container(
      color: const Color(0xff757575),
      child: Container(
        padding: const EdgeInsets.all(25),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              'Add task',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.lightBlueAccent, fontSize: 30.0),
            ),
            TextField(
              autofocus: true,
              textAlign: TextAlign.center,
              onChanged: (newText) {
                newTaskTitle = newText;
              },
            ),
            const SizedBox(height: 20),
            TextButton(
              child: const Text(
                'Add',
                style: TextStyle(color: Colors.white),
              ),
              style: TextButton.styleFrom(
                backgroundColor: Colors.lightBlueAccent,
              ),
              onPressed: () {
                print(newTaskTitle);
              },
            ),
          ],
        ),
      ),
    );
  }
}

If I set the String newTaskTitle as - late String newTaskTitle

late String newTaskTitle;

The following error is shown when I print the 'newTaskTitle' variable- "======== Exception caught by gesture =============================================================== The following LateError was thrown while handling a gesture: LateInitializationError: Local 'newTaskTitle' has not been initialized."

This is my first post on stackoverflow so thanks for your help!


Solution

  • The error is telling you exactly what the problem is. You are saying that you will be initializing the value of newTaskTitle at a 'later' time, but this must be before you use it. Typically you use a late variable initialization because you need some data passed into an object or widget to initialize it with.

    late String newTaskTitle;
    

    I can see in the TextField widget that when the text changes, you assign it to the newTaskTitle.

    TextField(
      ...
      onChanged: (newText) {
        newTaskTitle = newText;
      },
    ),
    

    If you first change the TextField text, then press the TextButton you should not see the error.

    You can also try just providing a default value when you create the vriable

    String newTaskTitle = '';
    

    I always recommend that if you are new to Dart and null-safety, complete this codelab which will save you many headaches: https://dart.dev/codelabs/null-safety