flutterdart

Can a Flutter Widget class be created without calling initState?


Which style of controller initialization in Flutter is better?

final _controller = TextEditingController();

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

or

late final TextEditingController _controller;

@override
void initState() {
  super.initState();
  _controller = TextEditingController();
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

In the first sample, the code is shorter and there's no need to override initState, so it should be better. But is it possible that the widget class would somehow be instantiated without calling initState? In that case, calling dispose would throw an error because of the uninitialized field.


Solution

  • "Better", as some have already said, is quite subjective as definition: in any case, initState is always called by Flutter itself, so it gets called anyway behind the curtains, whether you override it or not.
    I don't think there's any real difference between the two examples you posted, but it has happened to me that I was forced to choose the second style due to fields that needed to be initialized depending on other fields, so they could not be initialized at class level, but had to be declared late.