Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Dart

Learn Dart - 10 Code Examples & CST Typing Practice Test

Dart is a modern, object-oriented programming language developed by Google, optimized for building web, server, and mobile applications, particularly for Flutter. It emphasizes performance, strong typing, and productive development.

View all 10 Dart code examples →
Dart Theme Toggle and CounterDart Counter with HistoryDart Counter with Conditional ThemeDart Counter with Lambda ActionsDart Counter with Max LimitDart Counter with Timer Auto-IncrementDart Counter with User InputDart Counter with Event CallbacksDart Counter with Custom StepDart Counter with Persistent Storage

Learn DART with Real Code Examples

Updated Nov 21, 2025

Explain

Dart allows developers to write fast, maintainable, and expressive code.

It supports both just-in-time (JIT) compilation for development and ahead-of-time (AOT) compilation for production.

Dart combines object-oriented, functional, and reactive programming paradigms.

Core Features

Object-oriented with classes, mixins, and interfaces

Asynchronous programming with Futures and Streams

Optional static typing with type inference

Functional programming constructs like first-class functions

Comprehensive libraries for I/O, collections, and math

Basic Concepts Overview

Variables, constants, and type system

Control flow: if, for, while, switch

Functions and first-class functions

Classes, objects, and inheritance

Asynchronous programming with Futures and Streams

Project Structure

bin/ - main entry points for CLI apps

lib/ - shared libraries and code

test/ - unit and integration tests

web/ - web app entry for Flutter web

pubspec.yaml - package configuration

Building Workflow

Write Dart code in `.dart` files

Use `dart run` for executing scripts

Use `dart compile` for AOT compilation

Integrate with Flutter for mobile/web apps

Debug using IDE tools or command-line debugger

Difficulty Use Cases

Beginner: small scripts and console apps

Intermediate: Flutter mobile apps

Advanced: server-side apps and APIs

Expert: high-performance desktop apps and complex architectures

Community: contributing to open-source Dart and Flutter packages

Comparisons

Stronger typing and better tooling than JavaScript

Faster hot reload cycles than native development

Smaller ecosystem than Java or Python

Better performance in Flutter apps than other cross-platform tools

Syntax similar to C-style languages, easy to learn for Java/C# developers

Versioning Timeline

2011 - Dart language announced

2013 - Dart 1.0 released

2017 - Dart 2.0 introduced sound null safety

2018 - Flutter 1.0 release with Dart

2025 - Continuous improvements with Dart 3.x features

Glossary

Future: represents a value that will be available later

Stream: asynchronous sequence of data

Isolate: independent thread of execution

Pub: Dart package manager

AOT: Ahead-of-Time compilation

Installation Setup

Download Dart SDK from https://dart.dev/get-dart

Install via package managers (Homebrew, apt, choco)

Integrate with IDEs: VSCode, IntelliJ, Android Studio

Set environment variables for PATH

Verify installation using `dart --version`

Environment Setup

Install Dart SDK and Flutter SDK

Set environment variables for PATH

Configure IDE plugins for Dart/Flutter

Verify installation with `dart --version`

Optionally enable Dart DevTools

Config Files

pubspec.yaml - project dependencies and metadata

analysis_options.yaml - linter configuration

main.dart - entry point for apps

build.yaml - build configuration

.packages - generated package mapping

flutter.yaml - Flutter-specific project configuration

Cli Commands

dart run main.dart - run a Dart script

dart compile exe bin/main.dart - compile to executable

dart test - run tests

dart pub get - install dependencies

flutter run - run Flutter app

Internationalization

Use `intl` package for localization

Store strings in ARB or JSON files

Switch locales dynamically

Support right-to-left languages

Format numbers, dates, and currencies per locale

Accessibility

Use semantics widgets for screen readers

Provide proper labels and hints

Test with accessibility simulators

Ensure contrast and color accessibility

Handle input methods for diverse devices

Ui Styling

Flutter widgets provide UI elements

Themes and Material/Cupertino design

Layouts via Row, Column, Stack, Grid

Animations with built-in widgets or custom controllers

Responsive design for multiple platforms

State Management

Use classes and objects for state encapsulation

Flutter supports Provider, Riverpod, Bloc, and other patterns

Asynchronous data managed with Futures and Streams

Immutability encouraged for predictable state

Global vs local state handled via scope-specific objects

Data Management

Collections: List, Map, Set

JSON parsing via `dart:convert`

Use Streams for asynchronous data

Persist data using SQLite, Hive, or SharedPreferences

Use packages for advanced data operations

Architecture

Compiled to native code via AOT for mobile/desktop

JIT compilation for fast development and hot reload

Runs in Dart VM or compiles to JavaScript for web

Supports isolate-based concurrency

Rich runtime with garbage collection

Rendering Model

Compiled to native code via AOT

JIT compilation during development for hot reload

Runs on Dart VM or in browsers via Dart2js/DDC

UI rendering handled by Flutter framework

Isolate-based concurrency for safe multithreading

Architectural Patterns

Object-oriented with classes and mixins

Functional programming with first-class functions

Reactive programming with Streams

MVC, MVVM, and other patterns supported in Flutter

Event-driven and asynchronous programming

Real World Architectures

Flutter-based mobile apps for startups and enterprises

Server-side Dart APIs with shelf

Web apps compiled via Dart2js

Cross-platform desktop apps with Flutter

CLI tools and automation scripts

Design Principles

Optimized for developer productivity

Strongly typed with null safety

Cross-platform performance focus

Combines object-oriented and functional paradigms

Fast iteration via hot reload

Scalability Guide

Use modular architecture

Optimize build and compilation steps

Profile performance with DevTools

Leverage isolates for concurrency

Adopt state management patterns for large apps

Migration Guide

Update Dart SDK and Flutter SDK

Refactor deprecated APIs

Migrate to null safety if needed

Update packages to latest versions

Test thoroughly on all supported platforms

Performance Notes

Use AOT compilation for production

Minimize unnecessary object creation

Use const and final for immutable data

Avoid blocking the main isolate

Profile apps using Dart DevTools

Security Notes

Validate external input

Avoid unsafe reflection or dynamic code execution

Follow Flutter/Dart best practices for secure apps

Use HTTPS for network communication

Keep dependencies up to date

Monitoring Analytics

Use Dart DevTools for performance profiling

Track memory usage and isolates

Log app events and errors

Monitor asynchronous operations

Integrate with Firebase or custom analytics

Code Quality

Follow Dart style guide

Use `dart analyze` for static analysis

Write unit and integration tests

Use CI/CD for continuous integration

Document code with DartDoc

Practical Examples

Flutter mobile app with hot reload

Command-line data processing tool

Server-side API with Dart shelf

Web app compiled to JavaScript

Desktop app using Flutter for Windows/macOS/Linux

Troubleshooting

Check for null safety errors

Verify package imports in pubspec.yaml

Debug asynchronous code carefully

Resolve version conflicts in pub.dev packages

Ensure Dart SDK matches project requirements

Testing Guide

Unit testing with `package:test`

Widget testing for Flutter apps

Integration testing with `flutter_driver`

Mock dependencies for isolated testing

Run tests via `dart test` or IDE

Deployment Options

Compile to native binary for mobile/desktop

Compile to JavaScript for web

Package Flutter apps for iOS and Android

Deploy server-side Dart apps on cloud servers

Distribute CLI tools as executables

Tools Ecosystem

Dart SDK and Dart CLI tools

Flutter framework and CLI

pub.dev package manager

Dart DevTools for profiling and debugging

VSCode and IntelliJ IDEA plugins

Integrations

Flutter for cross-platform apps

Server-side Dart with shelf or aqueduct

Web apps via Dart2js or DDC

CI/CD pipelines for automated builds

Integration with Firebase and other cloud services

Productivity Tips

Leverage hot reload for fast iteration

Use const constructors for immutable widgets

Split code into reusable widgets and packages

Automate testing and deployment pipelines

Use Dart DevTools for profiling and debugging

Challenges

Build a command-line Dart tool

Create a small Flutter mobile app

Implement asynchronous API calls

Develop a web app using Dart2js

Contribute to a Dart or Flutter open-source package

Learning Path

Learn Dart basics: variables, types, control flow

Understand functions and classes

Master asynchronous programming with Futures and Streams

Practice Flutter app development

Build full-stack Dart applications

Skill Improvement Plan

Week 1: Dart syntax and simple scripts

Week 2: Object-oriented programming in Dart

Week 3: Futures, async/await, and Streams

Week 4: Flutter UI and state management

Week 5: Advanced Flutter features and deployment

Interview Questions

Explain null safety in Dart

What is the difference between `final` and `const`?

How do Futures and Streams work?

Explain the difference between AOT and JIT compilation

What are isolates in Dart?

Cheat Sheet

var x = 10 - variable declaration

final y = 20 - immutable variable

class MyClass {} - define class

Future<void> fetchData() async {} - async function

Stream<int> myStream = Stream.fromIterable([1,2,3]) - define stream

Books

Programming Dart by Google Developers

Flutter in Action

Dart Apprentice

Flutter Complete Reference

Beginning Flutter: A Hands-On Guide

Tutorials

Dart language tour on dart.dev

Flutter official tutorials

Learn Dart in Y Minutes

DartPad interactive coding exercises

YouTube Dart & Flutter tutorials

Official Docs

https://dart.dev/guides

https://api.dart.dev/

https://flutter.dev/docs

Community Links

Stack Overflow Dart and Flutter tags

Reddit r/dartlang and r/flutterdev

GitHub Dart and Flutter repositories

Flutter community forums and Discord servers

Twitter and Medium Dart/Flutter communities

Community Support

Official Dart website and documentation

Stack Overflow Dart and Flutter tags

Reddit r/dartlang and r/flutterdev

GitHub Dart and Flutter repositories

Flutter community forums and Discord channels

Monetization

Paid apps on App Store/Play Store

In-app purchases and subscriptions

Flutter plugins and packages on pub.dev

Freelance cross-platform app development

Enterprise mobile solutions

Future Roadmap

Improved null safety and type system features

Faster compilation and runtime optimizations

Better tooling and IDE support

Expanded Flutter and Dart ecosystem

Enhanced cross-platform capabilities

When Not To Use

Low-level system programming

Projects outside Flutter ecosystem if alternatives exist

Heavy computation without proper profiling

When small script size is critical for web apps

Projects relying on extensive libraries outside Dart ecosystem

Final Summary

Dart is a modern, fast, and versatile language.

Supports object-oriented and functional programming paradigms.

Designed for cross-platform app development with Flutter.

Strong typing with null safety enhances reliability.

Ideal for mobile, web, and server-side applications.

Faq

Is Dart object-oriented?

Yes, Dart is class-based and object-oriented.

Can Dart be used for server-side applications?

Yes, using Dart VM and server frameworks like shelf.

Does Dart support functional programming?

Yes, Dart supports first-class functions and higher-order functions.

What is Flutter?

Flutter is a UI toolkit built with Dart for cross-platform apps.

Does Dart have a garbage collector?

Yes, Dart VM manages memory automatically with garbage collection.

Code Sample Descriptions

1

Dart Theme Toggle and Counter

void main() {
    int count = 0;
    bool isDark = false;

    void updateUI() {
        print('Counter: $count');
        print('Theme: ${isDark ? 'Dark' : 'Light'}');
    }

    void increment() { count++; updateUI(); }
    void decrement() { count--; updateUI(); }
    void reset() { count = 0; updateUI(); }
    void toggleTheme() { isDark = !isDark; updateUI(); }

    updateUI();
    increment();
    increment();
    toggleTheme();
    decrement();
    reset();
}

Demonstrates a simple counter with theme toggling in Dart, runnable in console or Flutter environment.

Let’s Try →
2

Dart Counter with History

void main() {
    int count = 0;
    List<String> history = [];

    void updateUI() {
        print('Counter: $count');
        print('History: ${history.join(', ')}');
    }

    void increment() {
        count++;
        history.add('Incremented to $count');
        updateUI();
    }

    void decrement() {
        count--;
        history.add('Decremented to $count');
        updateUI();
    }

    void reset() {
        count = 0;
        history.clear();
        history.add('Counter reset');
        updateUI();
    }

    updateUI();
    increment();
    increment();
    decrement();
    reset();
}

A console-based counter that logs each increment/decrement action in a history list.

Let’s Try →
3

Dart Counter with Conditional Theme

void main() {
    int count = 0;
    bool isDark = false;

    void updateUI() {
        isDark = count % 2 == 0;
        print('Counter: $count');
        print('Theme: ${isDark ? 'Dark' : 'Light'}');
    }

    void increment() { count++; updateUI(); }
    void decrement() { count--; updateUI(); }
    void reset() { count = 0; updateUI(); }

    updateUI();
    increment();
    increment();
    increment();
    decrement();
    reset();
}

Counter that switches theme based on value thresholds in Dart console app.

Let’s Try →
4

Dart Counter with Lambda Actions

void main() {
    int count = 0;
    bool isDark = false;

    var updateUI = () => print('Counter: $count, Theme: ${isDark ? 'Dark' : 'Light'}');
    var increment = () { count++; updateUI(); };
    var decrement = () { count--; updateUI(); };
    var reset = () { count = 0; updateUI(); };
    var toggleTheme = () { isDark = !isDark; updateUI(); };

    updateUI();
    increment();
    toggleTheme();
    decrement();
    reset();
}

Demonstrates using Dart anonymous functions (lambdas) for counter actions and theme toggling.

Let’s Try →
5

Dart Counter with Max Limit

void main() {
    int count = 0;
    int maxLimit = 5;

    void updateUI() => print('Counter: $count');

    void increment() {
        if(count < maxLimit) count++;
        updateUI();
    }

    void decrement() { count--; updateUI(); }
    void reset() { count = 0; updateUI(); }

    updateUI();
    increment();
    increment();
    increment();
    increment();
    increment();
    increment(); // won't exceed maxLimit
    reset();
}

A counter that stops incrementing after reaching a maximum limit.

Let’s Try →
6

Dart Counter with Timer Auto-Increment

import 'dart:async';

void main() {
    int count = 0;

    Timer.periodic(Duration(seconds: 1), (timer) {
        count++;
        print('Counter: $count');
        if(count >= 5) timer.cancel();
    });
}

Automatically increments the counter every second using Dart Timer.

Let’s Try →
7

Dart Counter with User Input

import 'dart:io';

void main() {
    int count = 0;
    while(true) {
        print('Counter: $count');
        stdout.write('Enter i/d/r/q: ');
        String? input = stdin.readLineSync();
        if(input == 'i') count++;
        else if(input == 'd') count--;
        else if(input == 'r') count = 0;
        else if(input == 'q') break;
    }
}

A console-based counter that takes user input to increment, decrement, or reset.

Let’s Try →
8

Dart Counter with Event Callbacks

void main() {
    int count = 0;

    void onUpdate(int value) => print('Counter: $value');

    void increment(void Function(int) callback) {
        count++;
        callback(count);
    }

    void decrement(void Function(int) callback) {
        count--;
        callback(count);
    }

    void reset(void Function(int) callback) {
        count = 0;
        callback(count);
    }

    increment(onUpdate);
    increment(onUpdate);
    decrement(onUpdate);
    reset(onUpdate);
}

Uses callback functions to handle increment, decrement, and reset events.

Let’s Try →
9

Dart Counter with Custom Step

void main() {
    int count = 0;
    int step = 3;

    void updateUI() => print('Counter: $count');

    void increment() { count += step; updateUI(); }
    void decrement() { count -= step; updateUI(); }
    void reset() { count = 0; updateUI(); }

    updateUI();
    increment();
    decrement();
    reset();
}

A counter that can increment or decrement by a custom step value.

Let’s Try →
10

Dart Counter with Persistent Storage

import 'dart:io';

void main() {
    File file = File('counter.txt');
    int count = 0;
    if(file.existsSync()) {
        count = int.parse(file.readAsStringSync());
    }

    void updateUI() {
        print('Counter: $count');
        file.writeAsStringSync(count.toString());
    }

    void increment() { count++; updateUI(); }
    void decrement() { count--; updateUI(); }
    void reset() { count = 0; updateUI(); }

    updateUI();
    increment();
    decrement();
    reset();
}

Stores counter value in a file to persist between program runs (console app).

Let’s Try →

Frequently Asked Questions about Dart

What is Dart?

Dart is a modern, object-oriented programming language developed by Google, optimized for building web, server, and mobile applications, particularly for Flutter. It emphasizes performance, strong typing, and productive development.

What are the primary use cases for Dart?

Mobile app development with Flutter. Web applications and progressive web apps (PWAs). Server-side applications with Dart VM. Command-line tools and scripts. Cross-platform desktop applications

What are the strengths of Dart?

Fast compilation and runtime performance. Seamless cross-platform development with Flutter. Strong tooling support and IDE integration. Modern syntax and developer-friendly features. Large ecosystem and package management via pub.dev

What are the limitations of Dart?

Relatively smaller ecosystem compared to JavaScript or Python. Limited support for low-level system programming. Not as widely adopted outside Flutter ecosystem. Web performance depends on JavaScript compilation. Smaller talent pool compared to more established languages

How can I practice Dart typing speed?

CodeSpeedTest offers 10+ real Dart code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.