Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use this in a dart constructor with private variables

Tags:

flutter

dart

When I try to create a constructor in dart like Student(this._name) it doesn't work with private variables.

I have already tried using setters but it doesn't work either.

    class Student{

    var _id;
    var _name;

    Student(this.id, this.name);

    void set id(int id) => _id = id;
    void set name(String name) => _name = name;

    }
like image 808
Elias Dolinsek Avatar asked Jan 24 '19 18:01

Elias Dolinsek


People also ask

Can constructor use private variables?

In Javascript there's no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside.

How do you make a private constructor in Dart?

A constructor can be made private by using (_) underscore operator which means private in dart. class FooBar extends Foo { FooBar() : super. _(); // This will give compile time error. }

How do you define a private variable in Dart?

If an identifier starts with an underscore _ , it's private to its library. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.

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.


2 Answers

This is not supported because it would expose private implementation to the outside.

If you'd rename var _id; to var _userId; you would break code that uses your class just by renaming a private field.
See instead the comment below my answer.

  class Student{

    var _id;
    var _name;

    Student({this._id, this._name}); // error

    void set id(int id) => _id = id;
    void set name(String name) => _name = name;
  }

The alternative

  class Student{

    var _id;
    var _name;

    Student({int id, String name}) : _id = id, _name = name;

    void set id(int id) => _id = id;
    void set name(String name) => _name = name;
  }
like image 162
Günter Zöchbauer Avatar answered Oct 22 '22 09:10

Günter Zöchbauer


You can use this notation

class Student {
  String _id;
  String _name;

  Student({required String id, required String name})
      : _id = id,
        _name = name;
}
like image 45
awaik Avatar answered Oct 22 '22 10:10

awaik