乐闻世界logo
搜索文章和话题

Dart: How to Declare Constants?

2月7日 11:32
  • final: When you don't want to change a variable's value, use final. Once initialized, its value is immutable, but it must be assigned at runtime—meaning it can be initialized in constructors or other methods.
dart
final String name = 'John Doe';

Or assigned at runtime:

dart
final DateTime currentTime = DateTime.now();
  • const: Use const when defining a compile-time constant. A const constant requires all values to be known at compile time.
dart
const double pi = 3.14159;

You can also use const to create immutable collections at compile time:

dart
const List<int> numbers = [1, 2, 3, 4, 5];

In summary, choose between final and const based on whether the variable's value needs to be determined at compile time. If so, use const; if the assignment relies on runtime computation, use final.

标签:Dart