What I am trying to do is i am trying to create a texteditingcontroller field as much as user wants. But the issue is that when I print or try to use the value item.text
, it says null. How can I solve it?
class TextEditingModel {
TextEditingController hint = TextEditingController(text: '');
TextEditingModel ({this.hint});
TextEditingModel hintchange(){
print(hint);
return hint;
}
}
List<TextEditingModel> texteditingcontrollers = [];
RaisedButton(
child: Text('Add Controller',
onPressed: (){
setState(() {
TextEditingModel model = TextEditingModel();
texteditingcontrollers.add(model);
});
},),
for(final item in texteditingcontrollers)
TextFormField(controller: item.hintchange()),
CodePudding user response:
On TextEditingModel
at hintchange()
its return type TextEditingModel
and it should be same as hint
data type. Also while like to have default value and optional parameter on hint, like
class TextEditingModel {
TextEditingController? hint;
TextEditingModel({this.hint});
TextEditingController hintchange() {
return hint ?? TextEditingController(text: '');
}
}
And use case is working the way you did.
class Test extends StatefulWidget {
Test({Key? key}) : super(key: key);
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
List<TextEditingModel> texteditingcontrollers = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
for (final item in texteditingcontrollers)
TextFormField(controller: item.hintchange()),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
TextEditingModel model =
TextEditingModel(hint: TextEditingController(text: "Asda"));
texteditingcontrollers.add(model);
});
},
),
);
}
}