Dart

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

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!

Tags: dart, unit tests

Dart unit testing

Create a group of dart unit tests.

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

Tags: dart, files, dart package

Copy files from 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'));

Tags: dart, singleton, pattern, object oriented

Dart Singleton example

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
}

Tags: dart, JSON, object to JSON

How to convert an object to JSON

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

import 'dart:convert';

JsonEncoder().convert(yourObject)

Tags: dart, JSON, object

How to convert JSON to an Object

Converts JSON into an object.

import 'dart:convert';

JsonDecoder().convert(yourJson)

Tags: dart, data class

How to create a 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;
}

Tags: dart, conditional function

How to call a conditional function using Dart source code

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)();
}

Tags: dart, remove falsy

How to remove falsy values in Dart

Calls function depending on conditional values.

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

Tags: dart, difference, lists

How to find difference of 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();
}

Tags: dart, list, intersection

How to find Intersection using Dart source code

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);
}

Tags: dart, flatten

How to Flatten a list in Dart

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();
}

Tags: dart, truthy

Has truthy value

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);
}

Tags: dart, flutter, syntax highlight, StatelessWidget

Dart Syntax highlighting

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,
      ),
    );
  }
}

Tags: dart, directory, directory and files

How to copy directory and files recursively

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'));

Tags: dart, console, console messages, console colors

How to create terminal console color

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

Tags: dart, dart to javascript, dart export

Convert Dart to JavaScript

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';
}
}

150,000+ Installs

Want to use these Dart code snippets in your IDE?

Install one of our IDE integrations to 10x your productivity during your next coding project.