Varun S Athreya
Varun S Athreya

Reputation: 123

Is it good practice to keep all variables and functions private in flutter?

I am new to flutter, was going through a few good practices so had a doubt about making all the functions and variables private which won't be used outside the class.

Upvotes: 4

Views: 1370

Answers (2)

Dwi Kurnianto M
Dwi Kurnianto M

Reputation: 450

take a look here. https://dart.dev/guides/language/effective-dart/design#prefer-making-declarations-private

refereeing to dart.dev/guides its good to use private variables because they said

"PREFER making declarations private. A public declaration in a library—either top level or in a class—is a signal that other libraries can and should access that member. It is also a commitment on your library’s part to support that and behave properly when it happens.

If that’s not what you intend, add the little _ and be happy. Narrow public interfaces are easier for you to maintain and easier for users to learn. As a nice bonus, the analyzer will tell you about unused private declarations so you can delete dead code. It can’t do that if the member is public because it doesn’t know if any code outside of its view is using it."

But here's the thing, it all depends on your need, but remember to make security concern. It's not wrong to use private variables all over the place if you don't want other classes to access your variable, function, or class.

Edit : as per Flutter 3 and dart updates are coming. The statement about

As a nice bonus, the analyzer will tell you about unused private declarations so you can delete dead code.

Is no longer, relevant. Instead, the dart analyzer will tell you to use private variables inside the class, but outside class methods. Because there is no point in using private variables inside class methods since the variable will only be accessible from inside the class methods itself. 10 March 2023

Upvotes: 5

Shoaib Khan
Shoaib Khan

Reputation: 1060

It depends on the variable usage because if you are not going to use the variable outside of the widget then you should keep it private (Good practice [In my opinion]) otherwise make it public.

Making private is good because you can avoid variable conflict because sometimes you may have the same name variables in different widgets so if they are private then they will not conflict with each other.

Same for the functions as well.

-- This is my personal opinion you have the freedom to make your own decisions which to use.

Upvotes: 2

Related Questions