Learn the Basics of Dart
Dart is a popular programming language often used for web and mobile app development, especially with the Flutter framework.
- Hello Dart :
void main() {
print('Hello, Dart!');
}
Explanation:
void main()
is the entry point of a Dart program.print()
is used to display output to the console.
2. Variables and Data Types :
Dart has several data types, including int
, double
, String
, bool
, and more.
int age = 25;
double pi = 3.14;
String name = 'Alice';
bool isStudent = true;
3. Control Structures :
Dart supports common control structures like if
, else
, for
, while
, and switch
if (isStudent) {
print('Student');
} else {
print('Not a student');
}
for (var i = 0; i < 5; i++) {
print('Count: $i');
}
4. Functions :
Functions are defined using the functionName()
syntax.
String greet(String name) {
return 'Hello, $name!';
}
You can use the =>
syntax for one-liner functions.
int square(int x) => x * x;
5. Lists and Maps :
Lists hold a collection of items, while maps store key-value pairs.
List<int> numbers = [1, 2, 3];
Map<String, int> scores = {'Alice': 95, 'Bob': 88};
6. Classes and Objects :
Dart is an object-oriented language; you can create classes and objects.
class Person {
String name;
int age;
Person(this.name, this.age);
}
var alice = Person('Alice', 30);
7. Exception Handling :
Use try
, catch
, and finally
for error handling.
try {
// Code that may throw an exception
} catch (e) {
print('An error occurred: $e');
} finally {
// Code that always runs
}