Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Dart private class [duplicate]

Tags:

flutter

dart

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?

like image 204
Michel Feinstein Avatar asked Nov 28 '18 19:11

Michel Feinstein


People also ask

How do you access private members of a class in Dart?

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.

What is _$ in Dart?

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 {

Does Dart have private variables?

Instance variables are sometimes known as fields or properties. Unlike Java, Dart doesn't have the keywords public , protected , and private .

How do you declare a private class in darts?

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.


1 Answers

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);
...
like image 179
Rémi Rousselet Avatar answered Sep 24 '22 12:09

Rémi Rousselet