void main() {
// Declare variables(age, height, name, isStudent) of different types
int age = 25;
double height = 5.9;
String name = "Alic";
bool isStudent = true;
// Output their values
print("Name: $name");
print("Age: $age");
print("Height: $height");
print("Is a student? $isStudent");
}
----------------------------------------------------------------------------------------
In Dart, variables are used to store data that can be manipulated and retrieved throughout the program. Dart allows the declaration of variables using var, final, const, or specific data types like int, String, double, bool, etc. In this context, I'll cover 10 live programs that demonstrate how to declare and use basic variables in Dart.
dart
Copy code
void main() {
int number = 10; // Declaring an integer variable
print('Number: $number'); // Prints: Number: 10
number = 20; // Reassigning the variable
print('Updated Number: $number'); // Prints: Updated Number: 20
}
dart
Copy code
void main() {
String name = 'Alice'; // Declaring a string variable
print('Name: $name'); // Prints: Name: Alice
name = 'Bob'; // Reassigning the string variable
print('Updated Name: $name'); // Prints: Updated Name: Bob
}
dart
Copy code
void main() {
double price = 19.99; // Declaring a double variable
print('Price: \$${price}'); // Prints: Price: $19.99
price = 25.50; // Reassigning the double variable
print('Updated Price: \$${price}'); // Prints: Updated Price: $25.50
}
dart
Copy code
void main() {
bool isActive = true; // Declaring a boolean variable
print('Is Active: $isActive'); // Prints: Is Active: true
isActive = false; // Reassigning the boolean variable
print('Updated Is Active: $isActive'); // Prints: Updated Is Active: false
}
dart
Copy code
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry']; // Declaring a list variable
print('Fruits: $fruits'); // Prints: Fruits: [Apple, Banana, Cherry]
fruits.add('Mango'); // Adding an element to the list
print('Updated Fruits: $fruits'); // Prints: Updated Fruits: [Apple, Banana, Cherry, Mango]
}
dart
Copy code
void main() {
Map<String, int> ages = {'Alice': 30, 'Bob': 25}; // Declaring a map variable
print('Ages: $ages'); // Prints: Ages: {Alice: 30, Bob: 25}
ages['Charlie'] = 35; // Adding a new entry to the map
print('Updated Ages: $ages'); // Prints: Updated Ages: {Alice: 30, Bob: 25, Charlie: 35}
}
dart
Copy code
void main() {
final String country = 'USA'; // Declaring a final variable
print('Country: $country'); // Prints: Country: USA
// Uncommenting the following line will result in an error because 'country' is final
// country = 'Canada'; // Error: Can't assign to the final variable 'country'
}
dart
Copy code
void main() {
const double pi = 3.14159; // Declaring a constant variable
print('Pi: $pi'); // Prints: Pi: 3.14159
// Uncommenting the following line will result in an error because 'pi' is const
// pi = 3.14; // Error: Constant variables can't be assigned a value.
}
dart
Copy code
void main() {
var age = 25; // Declaring a variable with 'var' (type is inferred as int)
print('Age: $age'); // Prints: Age: 25
age = 30; // Reassigning the value (still an int)
print('Updated Age: $age'); // Prints: Updated Age: 30
}
dart
Copy code
void main() {
String? greeting = null; // Declaring a nullable variable
print('Greeting: $greeting'); // Prints: Greeting: null
greeting = 'Hello, Dart!'; // Assigning a non-null value to the nullable variable
print('Updated Greeting: $greeting'); // Prints: Updated Greeting: Hello, Dart!
}
Basic Variable Types:
int: Integer data type used for whole numbers (e.g., 10, 25, -5).
String: Represents a sequence of characters (e.g., 'Hello', 'Dart').
double: Used to represent floating-point numbers (e.g., 3.14, 19.99).
bool: Represents a boolean value (either true or false).
Collections:
List: An ordered collection of items (like an array) where the type of the elements can be specified.
Map: A collection of key-value pairs, where each key maps to a specific value.
Modifiers:
final: A variable declared as final can only be assigned once, and its value cannot be changed after initialization.
const: A const variable is a compile-time constant and is immutable, meaning its value cannot change during runtime.
var: Dart infers the type of the variable based on its initial value. The type is fixed once it's inferred, and it cannot change later.
nullable: By adding a ? to a type, the variable can hold null as a value. This is useful for optional or missing values.
Basic Data Types: Includes int, double, bool, String, List, Map, and Set.
Runes: Used for handling Unicode characters, such as emojis.
Symbol: Represents a compile-time constant symbol.
var: A variable whose type is inferred at compile time based on the assigned value.
dynamic: A variable whose type can change during runtime.
Nullable Types: Using ? after a type allows it to hold null.
const: Defines a compile-time constant that can never be changed.
final: Defines a variable that can only be set once but at runtime.
late: A variable declared with late can be initialized later. Useful for deferred initialization that’s required only once.
Variables name can be defined using different keywords and types based on their purpose and usage. Here's a Dart program that demonstrates various types of variables, including var, dynamic, const, final, and nullable types:
void main() {
// Integer variable using `int`
int age = 25;
print("Integer age: $age");
// Double variable using `double`
double height = 5.9;
print("Double height: $height");
// Boolean variable using `bool`
bool isStudent = true;
print("Boolean isStudent: $isStudent");
// String variable using `String`
String name = "Alice";
print("String name: $name");
// List variable using `List`
List<int> numbers = [1, 2, 3, 4, 5];
print("List numbers: $numbers");
// Map variable using `Map`
Map<String, String> person = {
'firstName': 'Alice',
'lastName': 'Johnson',
};
print("Map person: $person");
// Set variable using `Set`
Set<String> colors = {'red', 'green', 'blue'};
print("Set colors: $colors");
// Runes for Unicode characters
Runes emoji = Runes('\u{1F600}'); // 😀 emoji
print("Runes emoji: ${String.fromCharCodes(emoji)}");
// Symbol
Symbol symbol = #dartLang;
print("Symbol: $symbol");
// Using `var` (type inferred at compile-time)
var inferredInteger = 42;
print("Inferred Integer using var: $inferredInteger");
var inferredString = "Hello, Dart!";
print("Inferred String using var: $inferredString");
// Using `dynamic` (type can change at runtime)
dynamic variable = "Initial String";
print("Dynamic variable initially: $variable");
variable = 100; // Changing the type to int
print("Dynamic variable after changing to int: $variable");
// Nullable variables
int? nullableInt;
print("Nullable int (initially null): $nullableInt");
nullableInt = 50;
print("Nullable int after assignment: $nullableInt");
String? nullableString;
print("Nullable String (initially null): $nullableString");
nullableString = "Now I have a value!";
print("Nullable String after assignment: $nullableString");
// Constant variable using `const` (compile-time constant)
const double pi = 3.14159;
print("Constant pi: $pi");
// Final variable using `final` (runtime constant)
final DateTime currentTime = DateTime.now();
print("Final currentTime: $currentTime");
// Late variable (initialized later, only once)
late int delayedValue;
delayedValue = 10; // Must be initialized before use
print("Late initialized delayedValue: $delayedValue");
}
Output:
Integer age: 25
Double height: 5.9
Boolean isStudent: true
String name: Alice
List numbers: [1, 2, 3, 4, 5]
Map person: {firstName: Alice, lastName: Johnson}
Set colors: {red, green, blue}
Runes emoji: 😀
Symbol: Symbol("dartLang")
Inferred Integer using var: 42
Inferred String using var: Hello, Dart!
Dynamic variable initially: Initial String
Dynamic variable after changing to int: 100
Nullable int (initially null): null
Nullable int after assignment: 50
Nullable String (initially null): null
Nullable String after assignment: Now I have a value!
Constant pi: 3.14159
Final currentTime: 2024-10-25 12:34:56.789
Late initialized delayedValue: 10
In Dart programming, variables are used to store data values that can be manipulated during the program's execution. Below are the details of how variables are defined, the types of variables available, and the concepts related to them:
Variables in Dart are declared using the var, final, const, or explicit data types.
1. Using var
The var keyword lets Dart infer the variable's type based on its initial value.
Example:
var name = 'Dart'; // Dart infers the type as String
var age = 25; // Dart infers the type as int
2. Using Explicit Data Types
You can explicitly specify the data type of a variable.
Example:
String language = 'Dart';
int version = 3;
double rating = 4.7;
bool isAwesome = true;
3. Using final
Variables declared with final are immutable after they are initialized.
They are assigned a value at runtime, but you can’t reassign them.
Example:
final city = 'London';
4. Using const
Variables declared with const are compile-time constants.
The value must be known at compile time.
Example:
const pi = 3.14159;
Dart supports various data types for variables:
Numbers
int: Integer values.
int age = 30;
double: Decimal values.
double height = 5.9;
String
Textual data enclosed in single or double quotes.
String greeting = 'Hello, Dart!';
Boolean
Represents true/false values.
bool isRunning = false;
List
An ordered collection of items.
List<int> numbers = [1, 2, 3];
Map
A collection of key-value pairs.
Map<String, String> capitals = {'France': 'Paris', 'Japan': 'Tokyo'};
Set
A collection of unique items.
Set<int> uniqueNumbers = {1, 2, 3};
Null
Dart variables can have the value null unless explicitly non-nullable (in Dart 2.12 and later with null safety).
int? nullableAge = null;
Variables in Dart can be declared in different scopes:
Local Variables
Declared inside a function or block.
Example:
void printMessage() {
var message = 'Hello';
print(message);
}
Global Variables
Declared outside all functions and accessible throughout the file.
Example:
String appName = 'My App';
Instance Variables
Declared inside a class and belong to the instance of the class.
Example:
class Car {
String color;
}
Static Variables
Declared inside a class but shared among all instances.
Example:
class Math {
static const double pi = 3.14159;
}
Use final or const for variables that should not change.
Use meaningful variable names for clarity.
Enable null safety (? and !) to handle null values effectively.
void main() {
var city = "New York"; // Dart automatically infers the type as String
var temperature = 72.5; // Dart infers this as a double
print("City: $city");
print("Temperature: $temperature °F");
}
-----------------------------------------
In Dart, var is used to declare a variable with dynamic type inference. This means that Dart infers the type of the variable based on the assigned value, but once a type is inferred, the variable cannot change its type. However, var still behaves like a statically typed variable.
In addition, Dart also provides the dynamic type, which allows a variable to be reassigned with a different type. This is more flexible than var but comes with a tradeoff: type checks are done at runtime, rather than at compile time.
Here are 10 live programs demonstrating the use of var (dynamic type inference) in Dart:
dart
Copy code
void main() {
var number = 42; // Dart infers the type as int
print('Number is: $number'); // Prints: Number is: 42
// Uncommenting the following line will result in an error because 'number' is inferred as int
// number = "Hello"; // Error: A value of type 'String' can't be assigned to a variable of type 'int'
}
dart
Copy code
void main() {
var message = 'Hello, Dart!'; // Dart infers the type as String
print('Message: $message'); // Prints: Message: Hello, Dart!
// Uncommenting the following line will result in an error because 'message' is inferred as String
// message = 10; // Error: A value of type 'int' can't be assigned to a variable of type 'String'
}
dart
Copy code
void main() {
var numbers = [1, 2, 3]; // Dart infers the type as List<int>
print('Numbers: $numbers'); // Prints: Numbers: [1, 2, 3]
// Uncommenting the following line will result in an error because 'numbers' is inferred as List<int>
// numbers = ['a', 'b', 'c']; // Error: A value of type 'List<String>' can't be assigned to a variable of type 'List<int>'
}
dart
Copy code
void main() {
var sum = (int a, int b) => a + b; // Dart infers the type of 'sum' as Function
print('Sum: ${sum(5, 10)}'); // Prints: Sum: 15
}
dart
Copy code
void main() {
var number = 100; // Dart infers the type as int
print('Original number: $number'); // Prints: Original number: 100
number = 200; // Changing the value (same type)
print('Modified number: $number'); // Prints: Modified number: 200
}
dart
Copy code
class Car {
String brand;
int year;
Car(this.brand, this.year);
void displayInfo() {
print('Brand: $brand, Year: $year');
}
}
void main() {
var myCar = Car('Tesla', 2023); // Dart infers the type as Car
myCar.displayInfo(); // Prints: Brand: Tesla, Year: 2023
// Uncommenting the following line will result in an error because 'myCar' is inferred as Car
// myCar = 'Not a Car'; // Error: A value of type 'String' can't be assigned to a variable of type 'Car'
}
dart
Copy code
void main() {
var name = 'John'; // Dart infers the type as String
print('Name: $name'); // Prints: Name: John
name = null; // Since Dart allows `null` assignment to nullable types, no error
print('Name after null assignment: $name'); // Prints: Name after null assignment: null
}
dart
Copy code
void main() {
var pi = 3.14159; // Dart infers the type as double
print('Pi: $pi'); // Prints: Pi: 3.14159
// Uncommenting the following line will result in an error because pi is inferred as double
// pi = "Not a number"; // Error: A value of type 'String' can't be assigned to a variable of type 'double'
}
dart
Copy code
void main() {
var numbers = [10, 20, 30, 40];
// Using 'var' in a loop with type inference
for (var number in numbers) {
print(number); // Prints: 10, 20, 30, 40
}
}
dart
Copy code
void main() {
var person = {'name': 'Alice', 'age': 30}; // Dart infers the type as Map<String, dynamic>
print('Person: $person'); // Prints: Person: {name: Alice, age: 30}
// Modifying the map
person['city'] = 'New York';
print('Updated Person: $person'); // Prints: Updated Person: {name: Alice, age: 30, city: New York}
}
Type Inference: Dart automatically infers the type of a variable based on the initial value assigned to it. Once a type is inferred, the variable can no longer change its type.
Immutable with var: You cannot change the type of the variable after it has been assigned a value. However, you can modify the contents of mutable types (like List or Map).
Cannot Change Type: If you assign an int to a variable, Dart will infer it as int, and trying to assign a String later will result in an error.
var vs dynamic: The var keyword is used for type inference, and the type of the variable cannot change. On the other hand, the dynamic type allows the variable to hold values of any type, and its type is checked at runtime.
Collection Modification: You can modify the contents of a collection (e.g., List, Map) when the variable is declared with var, as long as the type remains consistent with the inferred type.
void main() {
int score = 50;
print("Initial Score: $score");
// Modifying the value of a variable
score = 75;
print("Updated Score: $score");
}
--------------------------------------
In this context, we’ll explore how to modify the values of variables of different types, including mutable and immutable types, final, and const variables.
Here are 10 live Dart programs demonstrating various ways to modify variable values:
dart
Copy code
void main() {
int num = 5; // Regular variable
print('Original value: $num');
num = 10; // Modifying the value of the variable
print('Modified value: $num'); // Prints: Modified value: 10
}
dart
Copy code
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print('Original list: $fruits');
fruits[1] = 'Mango'; // Modifying an element in the list
print('Modified list: $fruits'); // Prints: Modified list: [Apple, Mango, Cherry]
}
dart
Copy code
void main() {
Map<String, int> ages = {'Alice': 30, 'Bob': 25};
print('Original Map: $ages');
ages['Alice'] = 31; // Modifying the value associated with 'Alice'
print('Modified Map: $ages'); // Prints: Modified Map: {Alice: 31, Bob: 25}
}
dart
Copy code
void main() {
final int num = 100;
print('Original value: $num');
// Uncommenting the following line will result in a compile-time error:
// num = 200; // Error: Can't assign to the final variable 'num'
}
dart
Copy code
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print('Hi, I am $name and I am $age years old.');
}
}
void main() {
var person = Person('John', 30);
person.introduce(); // Prints: Hi, I am John and I am 30 years old.
// Modifying object properties
person.name = 'Alice';
person.age = 28;
person.introduce(); // Prints: Hi, I am Alice and I am 28 years old.
}
dart
Copy code
void main() {
List<int> numbers = [1, 2, 3, 4];
print('Original list: $numbers');
numbers.add(5); // Adding an element
numbers.removeAt(0); // Removing an element at index 0
print('Modified list: $numbers'); // Prints: Modified list: [2, 3, 4, 5]
}
dart
Copy code
void main() {
String message = 'Hello';
print('Original message: $message');
// Strings are immutable, so we need to assign a new value
message = message + ' World'; // Concatenating strings to modify the message
print('Modified message: $message'); // Prints: Modified message: Hello World
}
dart
Copy code
void main() {
List<List<int>> matrix = [
[1, 2],
[3, 4],
];
print('Original matrix: $matrix');
matrix[1][1] = 10; // Modifying an element inside a nested list
print('Modified matrix: $matrix'); // Prints: Modified matrix: [[1, 2], [3, 10]]
}
dart
Copy code
void modifyVariable(int value) {
value = value * 2; // Modifying the variable inside the function
print('Modified inside function: $value');
}
void main() {
int num = 5;
print('Original value: $num');
modifyVariable(num); // Passing the value to a function
// The value outside the function remains unchanged
print('Value outside function: $num'); // Prints: Value outside function: 5
}
dart
Copy code
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
print('Original list: $numbers');
// Modifying the list elements in a loop
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2; // Doubling each element
}
print('Modified list: $numbers'); // Prints: Modified list: [2, 4, 6, 8, 10]
}
Modifying Regular Variables: You can freely modify the value of regular variables (e.g., int, double, String).
Modifying List Elements: Lists are mutable, so you can modify their elements using indices or methods like add(), remove(), etc.
Modifying Map Values: You can change the values of specific keys in a Map by accessing the keys.
Modifying Object Properties: You can modify the properties of an object after it has been instantiated, unless those properties are final.
Modifying Immutable Types (String): Since strings are immutable in Dart, you need to assign new values (e.g., through concatenation or methods).
Modifying Values in Functions: When passing variables to a function, you modify the variable's value inside the function scope (pass-by-value).
Modifying Values in Loops: You can iterate over collections like lists and modify their elements in place.
void main() {
final String country = "Canada"; // Can be set once, and not changed
const double pi = 3.14159; // Compile-time constant
print("Country: $country");
print("Value of Pi: $pi");
// Trying to reassign a final or const variable will throw an error
// country = "USA"; // This will cause an error
}
-----------------------------------
Programs
In Dart, both final and const are used to define variables with constant values, but they have different use cases and behaviors:
final: A final variable can only be assigned once, and its value is determined at runtime. Once assigned, it cannot be changed. The variable can be initialized lazily (i.e., at runtime).
const: A const variable is a compile-time constant. The value of a const variable is determined at compile-time and must be known before runtime. You can use const to define values that are truly constant and cannot change.
Here are 10 live Dart programs that demonstrate the use of final and const in Dart:
dart
Copy code
void main() {
final String name = 'Alice'; // final variable
print(name);
// Uncommenting the following line will give an error because the value of a final variable cannot be changed
// name = 'Bob'; // Error: Can't assign to the final variable 'name'
}
dart
Copy code
void main() {
const double pi = 3.14159; // const variable
print(pi);
// Uncommenting the following line will give an error because const variables cannot be reassigned
// pi = 3.14; // Error: Constant variables can't be assigned a value.
}
dart
Copy code
void main() {
final List<String> fruits = ['Apple', 'Banana', 'Mango'];
fruits.add('Orange'); // You can modify the contents of the list
print(fruits);
// Uncommenting the following line will give an error because the variable itself cannot be reassigned
// fruits = ['Pineapple', 'Grapes']; // Error: Can't assign to the final variable 'fruits'
}
dart
Copy code
void main() {
const List<int> numbers = [1, 2, 3]; // const list
print(numbers);
// Uncommenting the following line will give an error because const variables are immutable
// numbers.add(4); // Error: The method 'add' isn't defined for the class 'List<int>'
}
dart
Copy code
class Person {
final String name; // final class property
Person(this.name);
void greet() {
print('Hello, $name');
}
}
void main() {
var person = Person('John');
person.greet(); // Prints: Hello, John
// Uncommenting the following line will give an error because the final variable cannot be reassigned
// person.name = 'Jane'; // Error: The setter 'name' isn't defined for the class 'Person'
}
dart
Copy code
class Circle {
final double radius;
static const double pi = 3.14159; // const static variable
Circle(this.radius);
double area() {
return pi * radius * radius;
}
}
void main() {
var circle = Circle(5);
print('Area of Circle: ${circle.area()}'); // Prints the area of the circle using const pi value
}
dart
Copy code
void main() {
final int heavyComputation = expensiveComputation();
print('Computed value: $heavyComputation');
}
int expensiveComputation() {
print('Performing expensive computation...');
return 42;
}
dart
Copy code
void main() {
const int x = 10;
const int y = 5;
// The sum of two constant values will be computed at compile time
const int sum = x + y;
print('Sum: $sum'); // Prints: Sum: 15
}
dart
Copy code
void main() {
const List<int> scores = [100, 90, 85]; // Compile-time constant array
print(scores); // Prints: [100, 90, 85]
}
dart
Copy code
void main() {
const bool isActive = true;
final String status;
if (isActive) {
status = 'Active'; // 'status' is initialized lazily
} else {
status = 'Inactive';
}
print('User status: $status'); // Prints: User status: Active
}
final:
Can be assigned a value only once.
The value is assigned at runtime.
Can be used for instance variables, method variables, or collections that can be modified (but the reference cannot change).
const:
The value is a compile-time constant.
Must be assigned at the time of declaration.
Cannot be changed or reassigned.
Can be used for values that are entirely constant and known at compile-time (like a constant mathematical value or a fixed string).
Use final when the value should only be set once but is determined at runtime.
Use const when the value is truly constant and should be determined at compile-time.
Here are 10 live examples that demonstrate the use of various variable types in Dart programming:
dart
Copy code
void main() {
var name = 'Alice'; // Dart infers String
var age = 30; // Dart infers int
var height = 5.7; // Dart infers double
print('Name: $name');
print('Age: $age');
print('Height: $height');
}
dart
Copy code
void main() {
String language = 'Dart';
int version = 3;
double rating = 4.5;
bool isPopular = true;
print('Language: $language');
print('Version: $version');
print('Rating: $rating');
print('Is it popular? $isPopular');
}
dart
Copy code
void main() {
final city = 'New York';
final int population = 8500000;
print('City: $city');
print('Population: $population');
}
dart
Copy code
void main() {
const pi = 3.14159;
const double gravity = 9.8;
print('Pi: $pi');
print('Gravity: $gravity');
}
dart
Copy code
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
fruits.add('Mango');
print('Fruits: $fruits');
}
dart
Copy code
void main() {
Map<String, int> stock = {'Apple': 50, 'Banana': 100, 'Cherry': 75};
stock['Mango'] = 40; // Adding a new key-value pair
print('Stock: $stock');
}
dart
Copy code
void main() {
Set<int> uniqueNumbers = {1, 2, 3, 3, 4};
uniqueNumbers.add(5); // Adding a new element
print('Unique Numbers: $uniqueNumbers');
}
dart
Copy code
void main() {
int? age; // Nullable variable
if (age == null) {
print('Age is null');
} else {
print('Age: $age');
}
age = 25;
print('Updated Age: $age');
}
dart
Copy code
String appName = 'My Dart App'; // Global variable
void main() {
printAppName();
}
void printAppName() {
print('Application Name: $appName');
}
dart
Copy code
class MathUtils {
static const double pi = 3.14159;
static double calculateCircleArea(double radius) {
return pi * radius * radius;
}
}
void main() {
double radius = 5.0;
double area = MathUtils.calculateCircleArea(radius);
print('Area of the circle with radius $radius: $area');
}
void main() {
String? address; // This variable can be null
address = null;
print("Address: $address");
}
Programs
--------------------------------
In Dart, null safety is a feature that ensures variables cannot contain null unless explicitly declared as nullable. Dart's null safety helps eliminate the issues associated with null references, making code more predictable and safe. Variables can be nullable if their type is followed by a ?.
Here are 10 live Dart programs demonstrating the usage of nullable variables (null safety) in Dart.
dart
Copy code
void main() {
int? nullableInt; // Nullable integer variable
print(nullableInt); // Prints null, because it's not initialized
nullableInt = 42; // Assigning a value to the nullable variable
print(nullableInt); // Prints 42
}
dart
Copy code
void main() {
String? nullableString = 'Hello, Dart'; // Nullable string variable
print(nullableString); // Prints 'Hello, Dart'
nullableString = null; // Assigning null
print(nullableString); // Prints null
}
dart
Copy code
void main() {
String? name = 'John';
if (name != null) {
print('Hello, $name'); // Will print: Hello, John
} else {
print('Name is null');
}
name = null; // Assigning null
if (name == null) {
print('Name is null'); // Will print: Name is null
}
}
dart
Copy code
void main() {
String? nullableString = null;
// If nullableString is null, assign default value 'Default String'
String result = nullableString ?? 'Default String';
print(result); // Prints 'Default String'
}
dart
Copy code
void main() {
List<int>? numbers = null; // Nullable list
if (numbers == null) {
print('List is null');
} else {
numbers.add(1);
print(numbers); // Will not be executed, because numbers is null
}
numbers = [1, 2, 3]; // Assigning a non-null list
print(numbers); // Prints [1, 2, 3]
}
dart
Copy code
String? getName() {
// Returning a nullable string
return null; // Could also return a name like 'John'
}
void main() {
String? name = getName();
if (name != null) {
print('Name is: $name');
} else {
print('No name provided'); // Prints: No name provided
}
}
dart
Copy code
class Person {
String? name; // Nullable instance variable
Person(this.name);
}
void main() {
Person? person = Person(null); // Creating an object with nullable property
if (person.name == null) {
print('Name is not provided'); // Prints: Name is not provided
} else {
print('Name: ${person.name}');
}
person.name = 'Alice'; // Assigning a value to the nullable name
print('Updated Name: ${person.name}'); // Prints: Updated Name: Alice
}
dart
Copy code
void main() {
List<String>? cities;
// Conditional check if cities list is null
cities = cities ?? ['New York', 'Los Angeles']; // Assigning default value if null
print(cities); // Prints: [New York, Los Angeles]
}
dart
Copy code
void greet(String? name) {
// If name is null, provide a default message
print(name ?? 'Hello, guest!');
}
void main() {
greet('Alice'); // Prints: Alice
greet(null); // Prints: Hello, guest!
}
dart
Copy code
void main() {
String? nullableName = null;
// Using the 'late' keyword, you can assert that the variable will be initialized later
String name = nullableName ?? 'Default Name'; // Using null-coalescing operator
print(name); // Prints: Default Name
}
Nullable Variable Declaration: You declare a nullable variable by adding a ? after the type. For example, String? means a nullable string. In contrast, String means a non-nullable string.
Null Check: You can check if a variable is null using if (variable != null) or use the null-coalescing operator (??) to provide a default value if a variable is null.
Default Value for Nullable Variables: Using the ?? operator, you can provide a default value when the variable is null.
Nullable Lists: Lists can also be nullable, and you can assign a null value to a list or provide a default list when it is null.
Nullable Return Type: Functions can return nullable types (String?), and you should handle the possibility of the function returning null.
Nullable Class Properties: You can define nullable properties inside classes. This allows for flexibility in object creation and handling optional values.
Nullable Function Parameters: Functions can accept nullable parameters, and you can provide default values or handle null values explicitly in the function body.
Late Keyword: The late keyword tells Dart that a variable will be initialized later. This is useful when dealing with non-nullable variables that are initially null.
Program 8: Working with Null Safety
void main() {
// Nullable variable
String? name;
print('Name: $name'); // prints null
// Non-nullable variable
String nonNullableName = 'John Doe';
print('Non-Nullable Name: $nonNullableName');
// Null check
if (name != null) {
print('Name is not null');
} else {
print('Name is null');
}
}
void main() {
String? nullableName; // This can hold a String or null
if (nullableName == null) {
print('Name is NULL');
} else {
print('Name: $nullableName');
}
}
Program 7: Working with Enums
enum Color { red, green, blue }
void main() {
// Get enum value
Color color = Color.green;
print('Color: $color');
// Get enum name
String colorName = color.name;
print('Color Name: $colorName');
// Get enum values
List<Color> colors = Color.values;
print('Colors: $colors');
}
Here are 20 live Dart programs demonstrating various ways to declare, use, and manipulate variables in Dart. These cover basic data types, dynamic types, constants, and more.
dart
Copy code
void main() {
int age = 25;
double height = 5.9;
String name = 'John';
print('Name: $name, Age: $age, Height: $height');
}
dart
Copy code
void main() {
dynamic variable = 42;
print(variable); // Output: 42
variable = 'Hello';
print(variable); // Output: Hello
}
dart
Copy code
void main() {
final String country = 'USA';
print(country);
// country = 'Canada'; // Error: Cannot reassign a final variable.
}
dart
Copy code
void main() {
const double pi = 3.14159;
print(pi);
// pi = 3.14; // Error: Cannot reassign a const variable.
}
dart
Copy code
void main() {
late String greeting;
greeting = 'Hello, Dart!';
print(greeting);
}
dart
Copy code
void main() {
String? name;
print(name); // Output: null
name = 'Alice';
print(name);
}
dart
Copy code
void main() {
int a = 5, b = 10, c = 15;
print('a: $a, b: $b, c: $c');
}
dart
Copy code
void main() {
String name = 'John';
int age = 30;
print('My name is $name and I am $age years old.');
}
dart
Copy code
void main() {
int x = 5, y = 3;
print('Sum: ${x + y}');
print('Difference: ${x - y}');
print('Product: ${x * y}');
print('Quotient: ${x / y}');
}
dart
Copy code
void main() {
bool isRaining = true;
bool isSunny = false;
print('Is it raining? $isRaining');
print('Is it sunny? $isSunny');
}
dart
Copy code
void main() {
List<int> numbers = [1, 2, 3];
print(numbers);
numbers.add(4);
print(numbers);
}
dart
Copy code
void main() {
Map<String, String> capitals = {'India': 'Delhi', 'USA': 'Washington'};
print(capitals['India']); // Output: Delhi
}
dart
Copy code
void main() {
Set<int> uniqueNumbers = {1, 2, 2, 3};
print(uniqueNumbers); // Output: {1, 2, 3}
}
dart
Copy code
void displaySum() {
int a = 10, b = 20;
print('Sum: ${a + b}');
}
void main() {
displaySum();
}
dart
Copy code
void main() {
var city = 'New York'; // Dart infers it as String
print(city);
city = 'Los Angeles';
print(city);
}
dart
Copy code
void main() {
int age = 30;
double temperature = 98.6;
String name = 'Alice';
print('Name: $name, Age: $age, Temperature: $temperature');
}
dart
Copy code
int globalVar = 100;
void main() {
int localVar = 50;
print('Global: $globalVar, Local: $localVar');
}
dart
Copy code
void main() {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
print('Sum of first 5 numbers: $sum');
}
dart
Copy code
void main() {
String firstName = 'John';
String lastName = 'Doe';
String fullName = firstName + ' ' + lastName;
print('Full Name: $fullName');
}
dart
Copy code
void main() {
String? name;
String greeting = name ?? 'Guest'; // Default to 'Guest' if name is null
print('Hello, $greeting');
}