本教程展示了如何在Dart中编写和声明私有变量。
Dart的私有变量
在Dart中没有私有关键字或私有变量。
在Dart中,你可以用下划线(_)来声明一个变量名,作为一个私有变量。
私有变量可以在同一个类中访问,而不是在类或文件之外。
在Dart中,你可以在类中声明私有变量
class Employee {
int _privateVariable = 0;
int id = 11;
displayMessage() {
print('$_privateVariable'); // 0
print('$id'); // 11
}
}
void main() {
Employee employee = Employee();
print(employee._privateVariable);
print(employee.id);
}
上面的代码是在单个文件中定义的
声明了一个私有变量,即在类中的变量(_)前加了一个下划线。
你可以访问类中的私有变量,也可以访问同一文件中的私有变量。
在java中同样的概念会产生一个错误,因为在类中声明的变量不能在类外访问。
在Dart中,你可以访问同一文件中的私有变量,即使变量被声明在不同的类中。
在Dart中,私有变量在库中有一个特殊的用途,就是提供隐私。
让我们在一个库中使用私有变量:
在hr.dart文件中声明hr库。
library hr;
class Employee {
int _privateVariable = 0;
int id = 11;
displayMessage() {
print('$_privateVariable'); // 0
print('$id'); // 11
}
}
void main() {
Employee employee = Employee();
print(employee._privateVariable);
print(employee.id);
}
在sales.dart 文件中使用hr.dart 库
在其他类中不能访问声明的hr库中的私有变量
如果你试图访问该私有变量,下面的代码会抛出一个错误。
下面是一段代码
import 'hr.dart';
void main() {
Employee emp = Employee();
emp.displayMessage(); // this works
print(emp._privateVariable); // throws compile time error
print(emp.id);
}
你可以在dart或flutter的库中使用私有变量来提供隐私。