Shown Error: NoSuchMethodError: The getter 'text' was called on null.
The getter 'text was called on null.
Receiver: null
Tried calling: text
How to create getter that get each controller value from the constructor? so that I can call it in the TextFormField
import 'package:flutter/material.dart';
class CustomTextFieldForm extends StatefulWidget {
final TextEditingController controller;
final String hintText;
final String errorMessage;
const CustomTextFieldForm({
Key? key,
required this.controller,
required this.hintText,
required this.errorMessage,
required Null Function(dynamic text) onChanged,
}) : super(key: key);
@override
_CustomTextFieldFormState createState() => _CustomTextFieldFormState();
}
class _CustomTextFieldFormState extends State<CustomTextFieldForm> {
get controller => null;
get errorMessage => null;
get hintText => null;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
validator: (String? value) {
if (value!.isEmpty) {
return errorMessage;
}
return null;
},
decoration: InputDecoration(
hintText: hintText,
hintStyle: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w200,
),
errorStyle: TextStyle(height: 0),
suffixIcon: controller.text.length > 0 ? IconButton(
onPressed: () {
controller.clear();
setState(() {});
},
icon: Icon(Icons.cancel, color: Colors.grey))
: null
),
);
}
}
CodePudding user response:
Use widget.variable_name
to access variable from statefulWidget
class to state
class.
TextEditingController get controller => widget.controller;
String get errorMessage => widget.hintText;
String get hintText => widget.errorMessage;
CodePudding user response:
you're trying to get the text from the widget constructor, which you set to a return of type Null
, so normally it will throw a null
.
what you need to do to make it work :
change this :
required Null Function(dynamic text) onChanged,
with this
required this.onChanged,
then declare that onChanged
function with other variables
final TextEditingController controller;
final String hintText;
final String errorMessage;
final Function(dynamic) onChanged;
Hope it helps.