Dart Code Samples

This collection is full of our team members’ most useful Dart code samples. Add these Dart snippets to Pieces for some extreme time-savers.

Add to Pieces

Check out the following Dart code examples ranging from Dart unit testing to converting Dart to JavaScript snippets. When you add these Dart snippets to Pieces you can use them in your IDE for some extreme time-savers.

We had some of our team members share their most useful Dart snippets. These Dart sample code snippets are great for any developer to improve their workflow. Additionally, we added some general-purpose snippets that we think some may just find helpful!

Dart unit testing

Tags: dart, unit tests

Create a group of dart unit tests.

group('group of tests', () {
  test('unit test', () {
    expect(true, true);
  });
});

Related links:

  1. How to write unit tests
  2. Dart test package

Copy files from Dart Package

Tags: dart, files, dart package

Uses Dart packaging URI to get the path to a package allowing one to pull assets/files from a Dart package. This ultimately allows “Flutter-like” asset bundling within a Dart package.

import 'dart:isolate';

var resolvedUri = await Isolate.resolvePackageUri(Uri(scheme: 'package', path: 'my_package/src/assets/cool_image.jpg'));

Related links:

  1. How to determine the Dart directory which a file is being executed
  2. How to find file in your Dart package

Dart Singleton example

Tags: dart, singleton, pattern, object oriented

Create a singleton class structure in Dart to ensure only one instance of a class is created. This can be used to update properties, enhance performance, and manage state.

class SingletonClass {
  static final SingletonClass _instance = SingletonClass._internal();

  factory SingletonClass() {
    return _instance;
  }

  SingletonClass._internal();

  String property1 = 'Default Property 1';
  String property2 = 'Default Property 2';
}

/// Example consuming the singleton class and accessing/manipulating properties
/// To evaluate the difference between a normal class and a singleton class, comment
/// out the factory constructor and _instance in SingletonClass and re-run.
void main() {
  /// Properties before
  String property1Before = SingletonClass().property1;
  String property2Before = SingletonClass().property2;

  print('property1Before: $property1Before'); // Default Property 1
  print('property2Before: $property2Before'); // Default Property 2

  /// Updating the properties
  SingletonClass().property1 = 'Updated Property 1';
  SingletonClass().property2 = 'Updated Property 2';

  /// Properties after
  print('property1After: ${SingletonClass().property1}'); // Updated Property 1
  print('property2After: ${SingletonClass().property2}'); // Updated Property 2
}

Related links:

  1. How to build a Singleton in Dart

How to convert an object to JSON

Tags: dart, JSON, object to JSON

This Dart code sample will convert an object into a JSON string.

import 'dart:convert';

JsonEncoder().convert(yourObject)

Related links:

  1. Dart examples code for a JsonEncoder class
  2. Dart code for JsonEncoder constructor

How to convert JSON to an Object

Tags: dart, JSON, object

Converts JSON into an object.

import 'dart:convert';

JsonDecoder().convert(yourJson)

Related links:

  1. How to decode a Json file in Flutter
  2. JsonDecoder class - sample Dart code
  3. Dart code example to decode a Json file in flutter

How to create a Dart data class

Tags: dart, data class

Creates a data class.

@immutable
class User {
  final String name;
  final int age;

  User(this.name, this.age);

  User copyWith({
    String name,
    int age,
  }) {
    return User(
      name ?? this.name,
      age ?? this.age,
    );
  }

  @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;

    return o is User && o.name == name && o.age == age;
  }

  @override
  int get hashCode => name.hashCode ^ age.hashCode;
}

Related links:

  1. How to create a immutable class
  2. Understanding data classes - IBM documentation

How to call a conditional function using Dart source code

Tags: dart, conditional function

Calls function depending on conditional values.

void func1(){
 print("func 1 called");
}

void func2(){
 print("func 2 called");
}

void main() {
 const someValue = 3;
 (someValue == 4? func1 : func2)();
}

Related links:

  1. How to call a function in a condition - Dart Flutter
  2. Dart conditional operators

How to remove falsy values in Dart

Tags: dart, remove falsy

Calls function depending on conditional values.

List compact(List lst) {
  return lst..removeWhere((v) => [null, false].contains(v));
}

Related links:

  1. Remove empty and fasly values from a List - Dart code examples
  2. Best way to filter null from a list using Dart coding language

How to find difference of lists

Tags: dart, difference, lists

Finds the difference between two lists.

List difference(Iterable a, Iterable b) {
  final s = b.toSet();
  return a.where((x) => !s.contains(x)).toList();
}

Related links:

  1. Different ways to check differences between two lists with Dart code examples
  2. Get difference of list - flutter Dart

How to find Intersection using Dart source code

Tags: dart, list, intersection

Finds elements that exist in two lists.

main() {
  final lists = [
    [1, 2, 3, 55, 7, 99, 21],
    [1, 4, 7, 65, 99, 20, 21],
    [0, 2, 6, 7, 21, 99, 26]
  ];

  final commonElements =
      lists.fold(
        lists.first.toSet(), 
        (a, b) => a.intersection(b.toSet()));

  print(commonElements);
}

Related links:

  1. toSet Method - Dart Snippets
  2. How to extract common elements from a list in Dart

How to Flatten a list in Dart

Tags: dart, flatten

Flatten a multi-dimensional list into a one-dimensional one.

List flatten(List lst) {
  return lst.expand((e) => e is List ? flatten(e) : [e]).toList();
}

Related links:

  1. Dart recursion
  2. How to flatten a list

Has truthy value

Tags: dart, truthy

Returns true if one element in a collection has a truthy value based on a predicate function.

bool some(Iterable itr, bool Function(T) fn) {
  return itr.any(fn);
}

Related links:

  1. Any Method - Iterable class
  2. Difference between any and every in Dart

Dart Syntax highlighting

Tags: dart, flutter, syntax highlight, StatelessWidget

These Dart code samples display code with syntax highlighting in a flutter app.

import 'package:flutter/material.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/github.dart';

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var code = '''main() {
  print("Hello, World!");
}
''';

    return HighlightView(
      // The original code to be highlighted
      code,

      // Specify language
      // It is recommended to give it a value for performance
      language: 'dart',

      // Specify highlight theme
      // All available themes are listed in `themes` folder
      theme: githubTheme,

      // Specify padding
      padding: EdgeInsets.all(12),

      // Specify text style
      textStyle: TextStyle(
        fontFamily: 'My awesome monospace font',
        fontSize: 16,
      ),
    );
  }
}

Related links:

  1. Flutter highlight widget

How to copy directory and files recursively

Tags: dart, directory, directory and files

Copies a directory (source) and all of its contents recursively to a new directory (destination)

import 'dart:io';
import 'package:path/path.dart' as path;

Future copyDirectoryRecursive(Directory source, Directory destination) async {
  await for (var entity in source.list(recursive: false)) {
    if (entity is Directory) {
      var newDirectory =
          Directory(p.join(destination.absolute.path, p.basename(entity.path)));
      await newDirectory.create();
      await copyDirectory(entity.absolute, newDirectory);
    } else if (entity is File) {
      await entity.copy(p.join(destination.path, p.basename(entity.path)));
    }
  }
}

// HOW TO USE IT:
// await copyDirectoryRecursive(Directory('cool_pics/tests'), Directory('new_pics/copy/new'));

Related links:

  1. Built-in function to copy a directory in Dart

How to create terminal console color

Tags: dart, console, console messages, console colors

Add colors like red, green, and blue to terminal output.

import 'dart:io';

import 'package:colorize/colorize.dart';

class Messages {
  // Prints
  static void printGood(String message) => print(Colorize(message).green());
  static void printWarning(String message) => print(Colorize(message).red());
  static void printInfo(String message) => print(Colorize(message).blue());

  // Stdouts
  static void outGood(String message) => stdout.write(Colorize(message).green());
  static void outWarning(String message) => stdout.write(Colorize(message).red());
  static void outInfo(String message) => stdout.write(Colorize(message).blue());

  // Returned colored strings
  static String good(String message) => Colorize(message).green().toString();
  static String warning(String message) => Colorize(message).red().toString();
  static String info(String message) => Colorize(message).blue().toString();
}

Related links:

  1. Color console output

Convert Dart to JavaScript

Tags: dart, dart to javascript, dart export

Transpile methods from Dart to JavaScript and tries calling the Dart methods that have been transpiled.

import 'package:js/js.dart';
import 'package:node_interop/node.dart';

void main() {
  setExport('hello', allowInterop(hello));
  setExport('numbers', allowInterop(numbers));
  setExport('circles', allowInterop(circles));
}

String hello() {
  return 'Hello hoomans!';
}

String numbers() {
  return 'test string';
}

String circles() {
  return 'second test';
}
}

Related links:

  1. Dart interfaces for JavaScript APIs

Want to use these Dart code samples in your IDE? Download our JetBrains plugin or VS Code extension to improve your developer productivity wherever you code.

Let us know what you think! Would you like to see other Dart snippets not listed on this page? Suggest a collection you'd like to see to help other developers speed up their workflows.