iDecode
iDecode

Reputation: 28976

Initialising an object at class level vs inside initState

I am creating a TextEditingController, and to initialise it, I can either do

class _HomePageState extends State<HomePage> {
  var _controller = TextEditingController();
  // ...
}

or

class _HomePageState extends State<HomePage> {
  var _controller;

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

  // ...
}

And in both cases I can use dispose method to clean the _controller. Is there any difference between two approaches when it comes to memory allocation, will dispose be able to dispose the one created at class level?

Upvotes: 1

Views: 45

Answers (1)

MickaelHrndz
MickaelHrndz

Reputation: 3842

You can always refer to the widgets documentation. TextEditingController's doc sample initializes it on creation.

There is almost no difference because initState is the first thing done after the State creation (see widget lifecycle).

EDIT : To answer your comment, your link is a cookbook, so it's more hands-on and less in the theory. Also, it can be dirty or broken apparently, which you can find out if you scroll to the bottom.

I feel your pain about documentation, a lot of the times you get clearer info from "unofficial" sources. You can still refer to it though, but yeah you have to keep that critical spirit.

Anyway, the cleanest way is to initialize on creation, if you can. Initialization in initState is typically done when you need the BuildContext or some extra business logic beforehand.

Upvotes: 1

Related Questions