I don't need to do many things with TextEditingController but want to show the initial text. And I feel like creating StatefulWidget is too much for that. Here's what I want my code looks like
// In StatelessWidget
TextField(
controller: TextEditingController(),
)
But every tutorials and blog posts I've seen use TextEditingController in StatefulWidget and dispose them in the dispose method. But I can't dispose them if I use like the above
If you want to use TextEditingController
, there is no way around except to use a StatefulWidget
if you want to avoid memory leaks.
However, if you see alot of boilerplate in this approach, you can use HookWidget
(flutter_hooks) which gives you access to TextEditingController
in a simple way and disposes it for you,here is a comparison:
using StatefulWidget
:
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
TextEditingController controller;
FocusNode focusNode;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
child: TextField(
focusNode: focusNode,
controller: controller,
),
),
),
);
}
@override
void initState() {
controller = TextEditingController();
focusNode = FocusNode();
super.initState();
}
@override
void dispose() {
controller.dispose();
focusNode.dispose();
super.dispose();
}
}
using HookWidget
:
class Test extends HookWidget {
@override
Widget build(BuildContext context) {
final focusNode = useFocusNode();
final controller = useTextEditingController();
return Scaffold(
body: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
child: TextField(
focusNode: focusNode,
controller: controller,
),
),
),
);
}
}