I want a default empty controller for my custom text field but its not allowing with both ways
CodePudding user response:
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.
CodePudding user response:
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();
}
}