In Flutter we commonly have something like this:
class MyStatefulWidget extends StatefulWidget {
@override
_MyState createState() => _MyState();
}
class _MyState extends State<MyStatefulWidget> {
void doSomething() => print('hi');
@override
Widget build(BuildContext context) {
return Container();
}
}
So _MyState
is declared with a _
, which makes it library private.
So how come the Flutter render engine can use _MySate
if it's sopposed to be private?
It's funny because I can access doSomething()
from other files, but if I make it _doSomething()
, I can't access it anymore...So how come I can access a public method from a private class, but I can't access a private method from a private class?
In Dart, privacy is at the library level, not the class level. You can access a class's private members from code outside of that class as long as that code is in the same library where the class is defined. (In Java terms, Dart has package private.
By convention generated code starts with “_$”, to mark it as private and generated. So the generated implementation will be called “_$User”. To allow it to extend “User” there will be a private constructor for this purpose called “_”: === user.dart ===abstract class User {
Instance variables are sometimes known as fields or properties. Unlike Java, Dart doesn't have the keywords public , protected , and private .
In dart, you can declare a variable name with an underscore(_) as a private variable. Private variables are accessed inside the same class, not outside the classes or files.
While _MyState
is private, StatefulWidget
and State
are not.
The framework doesn't manipulate _MyState
, it manipulates these lower layer that he has access to, with a well-defined prototype.
This basically sums up into:
StatefulWidget widget;
State foo = widget.createState();
foo.initState();
final newWidget = foo.build(this);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With