Dart Basic Syntax
Understanding the basic syntax and structure of Dart is essential for writing and organizing code. Dart syntax is clean, simple, and inspired by languages like JavaScript, Java, and C++, making it easy to learn, especially if you're familiar with other object-oriented languages.
Here’s a rundown of the core components of Dart’s syntax and structure:
1. Main Function
The main()
function is the entry point of every Dart program. Dart will look for this function to start execution.
- void: Indicates that
main()
does not return a value. - print: A built-in function that outputs text to the console.
2. Variables and Data Types
Dart supports both type inference and explicit typing. To declare variables, use either var
, final
, or const
.
- var: The type is inferred based on the assigned value.
- final: Used for variables whose values won’t change after initialization.
- const: Used for compile-time constants that never change.
3. Functions
Functions are reusable blocks of code. Dart supports both named parameters and positional parameters.
Optional Named Parameters:
Optional Positional Parameters:
4. Control Flow Statements
Dart provides the typical control flow statements such as if
, else
, for
, while
, and switch
.
5. Collections: Lists, Sets, and Maps
Collections are used to store multiple values in Dart. The primary types are List
, Set
, and Map
.
6. Classes and Objects
Dart is an object-oriented language that supports classes and objects. Classes are blueprints for creating objects.
7. Comments
Comments are used to add explanations or to disable code temporarily.
8. String Interpolation
Dart uses the ${variable}
syntax for string interpolation. If the variable is a simple identifier, you can omit the curly braces.
9. Arrow Functions
For concise functions, you can use arrow syntax (=>
) for single-line functions.
Summary of Dart Syntax
- The main function is the entry point.
- Variables can be declared with
var
,final
, orconst
. - Functions support named and positional parameters.
- Control structures include if-else, for, while, and switch.
- Dart collections include List, Set, and Map.
- Classes define objects with fields and methods.
- String interpolation and arrow functions allow for more concise code.
These components provide the fundamental structure and syntax for writing effective Dart code.