Reputation: 47
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
)
],
)
);
}
}
Upvotes: 1
Views: 7040
Reputation: 15335
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.
Upvotes: 1
Reputation: 1277
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.
Upvotes: 6
Reputation: 1939
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
: "")
],
)),
),
);
}
}
Upvotes: 0