Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

like image 861
Varun S Athreya Avatar asked Oct 23 '25 19:10

Varun S Athreya


1 Answers

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

like image 78
Dwi Kurnianto M Avatar answered Oct 26 '25 11:10

Dwi Kurnianto M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!