In Dart, keywords are reserved words with special meanings that cannot be used as identifiers (such as variable names, class names, or method names). Here's a categorized list of Dart keywords:
if
else
switch
case
default
for
while
do
continue
break
return
yield
int
double
num
bool
String
dynamic
var
class
extends
implements
mixin
with
abstract
interface
new
this
super
async
await
sync
yield
final
const
late
static
try
catch
finally
throw
null
required
is
as
true
false
assert
enum
import
export
library
part
set
get
operator
typedef
These words have specific meanings in particular contexts:
covariant
deferred
external
factory
Function
show
hide
These words are reserved but not currently used in Dart:
native
In Dart, the final and const keywords are used to declare variables that have immutable values, but they have distinct purposes and behaviors. Here's a breakdown:
A final variable can only be set once. Its value is determined at runtime.
Once assigned, its value cannot be changed, but it is not required to be a compile-time constant.
It is commonly used when the value of a variable is only known during runtime but should remain constant thereafter.
Example:
dart
Copy code
void main() {
final currentTime = DateTime.now(); // Value is set at runtime.
print(currentTime);
// currentTime = DateTime.now(); // This will throw an error: Cannot reassign a final variable.
}
A const variable is a compile-time constant. Its value must be known at compile time, and it is deeply immutable (including any objects it refers to).
const is more restrictive than final.
A const variable can also be used to define constant expressions or objects.
Example:
dart
Copy code
void main() {
const pi = 3.14159; // Compile-time constant.
print(pi);
// const time = DateTime.now(); // This will throw an error: DateTime.now() is not a compile-time constant.
}
Object Example:
dart
Copy code
void main() {
// Final allows runtime assignment:
final list1 = [1, 2, 3];
list1[0] = 10; // Modifying content is allowed.
print(list1); // [10, 2, 3]
// Const ensures full immutability:
const list2 = [1, 2, 3];
// list2[0] = 10; // Error: Cannot modify an unmodifiable list.
print(list2); // [1, 2, 3]
}
Use final when the value isn't known until runtime but should not change after being assigned.
Use const when the value is immutable and known at compile-time.
In all programming languages data types and variables are two related but distinct concepts.
Data types are classifications of data (such as int, String), specifying the kind of data.
Variables are named placeholders that store data, each associated with a data type that defines the nature of the data it holds.
A data type defines the kind of data a variable can hold.
It determines the operations you can perform on that data and the amount of memory it will occupy.
Dart has several built-in data types like int, double, bool, String, List, Map, and Set, as well as the dynamic type, which allows for values of any type.
Data types provide a structure to the values, ensuring consistency, helping with error detection, and optimizing memory usage.
Example of Data Types in Dart:
int age = 30; // 'int' is the data type
double height = 5.9; // 'double' is the data type
String name = "Alice"; // 'String' is the data type
A variable is a name or identifier for a storage location in memory that holds data.
Variables act as containers or placeholders for data values.
When you declare a variable, you usually assign it a data type (though var and dynamic can be used to let Dart infer or change the type).
Variables are mutable by default, meaning you can change their values, except if declared as final or const, in which case their values cannot be modified after initialization.
Example of Variables in Dart:
int age = 30; // 'age' is a variable of type 'int'
double height = 5.9; // 'height' is a variable of type 'double'
String name = "Alice"; // 'name' is a variable of type 'String'
dart
Copy code
void main() {
var items = [1, 2, 'Dart', true, 3.14];
items.add('Flutter');
items.remove(2);
for (var item in items) {
print('Item: $item, Type: ${item.runtimeType}');
}
}
dart
Copy code
void main() {
String? userName; // Nullable variable
userName ??= 'Guest'; // Assign only if null
int? age = null;
age = age ?? 18; // Assign default value if null
print('User: $userName, Age: $age');
}
dart
Copy code
void main() {
final apiEndpoint = 'https://api.example.com/data';
print('Fetching data from: $apiEndpoint');
// Simulated API response
final data = {'id': 1, 'name': 'Dart'};
print('Response: $data');
}
dart
Copy code
void main() {
const appName = 'Advanced Dart App';
const int maxRetries = 3;
print('App: $appName, Max Retries: $maxRetries');
for (int i = 1; i <= maxRetries; i++) {
print('Retry #$i');
}
}
dart
Copy code
void main() {
List<int> numbers = [10, 20, 30, 40];
int sum(List<int> nums) => nums.reduce((a, b) => a + b);
print('Numbers: $numbers');
print('Sum: ${sum(numbers)}');
}
dart
Copy code
void main() {
Map<String, Map<String, dynamic>> userProfiles = {
'user1': {'name': 'Alice', 'age': 25},
'user2': {'name': 'Bob', 'age': 30},
};
userProfiles['user3'] = {'name': 'Charlie', 'age': 35};
for (var userId in userProfiles.keys) {
print('ID: $userId, Profile: ${userProfiles[userId]}');
}
}
dart
Copy code
void main() {
List<int> numbers = [1, 2, 3, 4, 3, 2, 1];
Set<int> uniqueNumbers = numbers.toSet();
print('Original List: $numbers');
print('Unique Numbers: $uniqueNumbers');
}
dart
Copy code
void main() {
String? input = '42';
int? parsedValue = int.tryParse(input!);
if (parsedValue != null) {
print('Parsed Value: $parsedValue');
} else {
print('Invalid input');
}
}
dart
Copy code
String globalMessage = 'Hello from Global!'; // Global variable
class Greeter {
String instanceMessage;
Greeter(this.instanceMessage);
void greet() {
print(globalMessage);
print(instanceMessage);
}
}
void main() {
var greeter = Greeter('Hello from Instance!');
greeter.greet();
}
dart
Copy code
class Counter {
static int _count = 0;
static void increment() => _count++;
static void decrement() => _count--;
static int getCount() => _count;
}
void main() {
Counter.increment();
Counter.increment();
Counter.decrement();
print('Current Count: ${Counter.getCount()}');
}
These examples showcase more advanced scenarios:
Dynamic list handling and runtime type checks.
Null safety with the ?? and ??= operators.
Real-world use of final and const in API endpoints and configuration.
Data manipulation using nested maps, sets, and custom functions.
Combining global, instance, and static variables for reusable logic.