Dart logo

Dart Beginner

Client-optimized language — fast compilation, sound null safety, and the foundation powering the Flutter toolkit.

1 Variables & Initialization

Dart handles data allocation through explicit declarations or type inference with var. It uses final for runtime constants and const for compile-time constraints.

dart · main.dart
void main() {
  var url = 'https://vidux.sh'; // Type inferred as String
  int port = 443;               // Explicit standard assignment

  final currentTime = DateTime.now(); // Evaluated at runtime
  const maxRetries = 3;               // Fixed at compile-time

  print("Targeting $url on port $port"); // String interpolation
}

2 Built-in Types Ecosystem

All data structural types inherit behaviors from the master Object reference. Numbers are cleanly separated between integer fields and floating points.

int / double Numeric architectures (num) int delay = 200;
String UTF-16 string vectors String app = 'vidux';
bool Compile boolean flags bool isActive = false;
List<T> Ordered array collections [1, 2, 3]
Map<K, V> Linked hash collection grids {'key': 'value'}
dynamic Bypasses static type checks Avoid using in production

3 Conditionals & Null-Aware Operators

Dart guarantees Sound Null Safety. Types are non-nullable by default unless explicitly appended with the nullability flag (?).

dart · safety.dart
String? username; // Can store a String or hold null safely

// Null-aware assignment: assign value only if currently null
username ??= 'guest_user';

// Conditional method invocation chain execution fallback
int nameLength = username?.length ?? 0;

if (nameLength > 5) {
  print('Standard profile verified');
} else {
  print('Compact moniker allocated');
}

4 Loops & Collection Iterators

Dart handles typical loops natively, but it also provides clean, concise patterns specifically for processing collection streams.

dart · loops.dart
var endpoints = ['api/v1', 'api/v2', 'api/v3'];

// Standard sequential pointer iteration loop iteration loop
for (var i = 0; i < endpoints.length; i++) {
  print('Index lookup: ${endpoints[i]}');
}

// Clean element iteration architecture matching collections
for (var route in endpoints) {
  print('Route verified: $route');
}

// Arrow function shortcut block interface iteration structures
endpoints.forEach((route) => print('Callback processing: $route'));

5 Functions & Optional Parameters

Functions wrap definitions clearly. Named optional parameters are enclosed in curly brackets ({}) and support default fallback assignments.

dart · functions.dart
// Named arguments declared inside brackets; explicit default value mapping
void configureWidget({required String id, bool visible = true}) {
  print('Rendering target context ID: $id (Display status: $visible)');
}

// Single line expression declaration shorthand template
int computeSquare(int x) => x * x;

void main() {
  // Executing calls leveraging distinct parameter tags
  configureWidget(id: 'main_viewport', visible: false);
}

6 Classes & Modern Constructors

Dart features implicit interfaces for all classes. Constructors use syntactic sugar to directly map parameters to internal instance properties.

dart · objects.dart
class ProjectToken {
  final String title;
  int databaseId;

  // Shorthand constructor matching properties instantly
  ProjectToken(this.title, this.databaseId);

  // Named constructor alternative for custom mapping logic
  ProjectToken.anonymous()
      : title = 'Generic Project',
        databaseId = 0;
}

void main() {
  var token = ProjectToken('ScratchMap', 101); // No 'new' keyword required
}
Properties prefixed with an underscore (e.g., _privateField) are **strictly library-private**, meaning they are encapsulated and hidden from external file imports.

7 Asynchronous Programming (Futures)

Dart uses Future objects to handle non-blocking asynchronous operations, combining clean async and await syntactic workflows.

dart · async.dart
// Emulates a delayed API response hook yielding String metrics
Future<String> fetchNetworkData() async {
  await Future.delayed(Duration(seconds: 2));
  return 'Synchronized core payload';
}

void main() async {
  print('Initiating worker query...');
  var result = await fetchNetworkData();
  print('System resolution message response: $result');
}

8 Cascade Notation & Extensions

The cascade operator (..) lets you chain multiple operations on the same object sequence, saving you from writing repetitive variable lookups.

dart · advance.dart
class LogBuffer {
  String scope = '';
  int linesCount = 0;
  void flush() => print('Flushed $linesCount units for $scope');
}

void main() {
  // Instantiates, updates properties, and fires methods in one chain
  var logger = LogBuffer()
    ..scope = 'project'
    ..linesCount = 142
    ..flush();
}
With Dart fundamentals down, you are ready to construct fast, responsive cross-platform user interfaces using the **Flutter engine UI library framework**.