0
votes

I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null. Receiver: null Tried calling: text See also: https://flutter.dev/docs/testing/errors

import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}
3
Normally you should explain what you have tried to solve it, but I alas I feel this error is quite vague. In a perfect world the error would say "textController has not been initialized" - C. Skjerdal

3 Answers

5
votes

It looks like you have not initialized your TextEditingController. You can initialize it at the time of declaring it like this,

TextEditingController textController = TextEditingController();

It is essential to initialize it before using it otherwise the instance textController remains null and textController.text is called on null.

1
votes

You are getting the error because textController is not yet instantiated, hence its value is null. You can make the property call null-aware to skip the error:

textController?.text

you'll get other errors though. After fixing the other errors the app will work but I doubt it does what you want.

0
votes

You had a couple of errors in there, so i ll just post the whole, working code. You were missing a MaterialApp and Scaffold Widget. These are required for your App to run (Scaffold is required on every screen).

As for your TextController, you have to check if the controller exists, and if the controller.text has a value, otherwise you try to assign null when your widget is expecting a String. I solved that with a ternery expression here.

condition ? if yes block : if no block

Full Code:

import 'package:flutter/material.dart';

void main() {
  runApp(NewApp());
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
            child: Column(
          children: <Widget>[
            TextField(
              controller: textController,
            ),
            Text(textController != null && textController.text != null
                ? textController.text
                : "")
          ],
        )),
      ),
    );
  }
}