'default texteditingcontroller for custom text field widget
Solution 1:[1]
You cannot have a const constructor and use a non constant default value. Therefore you would have to remove the const keyword before CustomTextField. But you can also not have a non-constant value as an optional parameter.
So a suggestion is to change the stateless widget to a stateful widget and initialize the controller in the init() method if no controller is provided with the the contructor.
Solution 2:[2]
It's better to set a default controller like this, so we can dispose it to prevent memory leaks:
import 'package:flutter/material.dart';
class CustomTextField extends StatefulWidget {
const CustomTextField({
Key? key,
this.controller,
}) : super(key: key);
final TextEditingController? controller;
@override
State<CustomTextField> createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = widget.controller ?? TextEditingController();
}
@override
void dispose() {
if (widget.controller == null) {
// if we made the controller ourselves, we dispose it ourselves
// but if it's made outside of this widget, it should be disposed outside
_controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mahdi Arabpour |


