Pieces loves Dart, and with the following collection, we had some of our team members share their most useful Dart snippets. 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 unit tests.
group('group of tests', () {
test('unit test', () {
expect(true, true);
});
});
Related links:
- https://docs.flutter.dev/cookbook/testing/unit/introduction#5-combine-multiple-tests-in-a-group
- https://pub.dev/packages/test
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:
- https://stackoverflow.com/questions/69391937/is-there-a-way-to-determine-the-directory-of-the-file-in-which-the-dart-file-is
- https://www.reddit.com/r/dartlang/comments/t1tfrx/how_to_find_files_in_my_package/
Singleton
Tags: dart, singleton, pattern, object oriented
Creates 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:
- https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart
Convert to JSON
Tags: dart, JSON, object to JSON
Converts an object into a JSON string.
import 'dart:convert';
JsonEncoder().convert(yourObject)
Related links:
- https://api.flutter.dev/flutter/dart-convert/JsonEncoder-class.html
- https://api.dart.dev/stable/2.1.1/dart-convert/JsonEncoder/JsonEncoder.html
Convert JSON to an Object
Tags: dart, JSON, object
Converts JSON into an object.
import 'dart:convert';
JsonDecoder().convert(yourJson)
Related links:
- https://flutteragency.com/how-to-decode-json-in-flutter/
- https://api.dart.dev/stable/2.17.3/dart-convert/JsonDecoder-class.html
- https://stackoverflow.com/a/58393044
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:
- https://api.flutter.dev/flutter/meta/Immutable-class.html
- https://www.ibm.com/docs/en/zos/2.4.0?topic=classes-understanding-data
Conditional function call
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:
- https://stackoverflow.com/questions/68880685/flutter-how-to-call-a-function-in-a-condition
- https://www.w3adda.com/dart-tutorial/dart-conditional-operators
Remove falsy values
Tags: dart, remove falsy
Calls function depending on conditional values.
List compact(List lst) {
return lst..removeWhere((v) => [null, false].contains(v));
}
Related links:
- https://devsheet.com/remove-empty-and-falsey-values-from-a-list-in-dartflutter/
- https://stackoverflow.com/questions/34513924/what-is-the-best-way-to-fillter-null-from-a-list-in-dart-language
Difference
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:
- https://www.cloudhadoop.com/dart-lists-difference/
- https://stackoverflow.com/questions/57633439/get-difference-of-lists-flutter-dart
Intersection
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:
- https://api.dart.dev/stable/2.17.3/dart-core/Set/toSet.html
- https://stackoverflow.com/questions/59431806/extract-common-elements-from-lists-in-dart
Flatten
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:
- https://www.geeksforgeeks.org/dart-recursion/
- https://stackoverflow.com/questions/15413248/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:
- https://api.flutter.dev/flutter/dart-core/Iterable/any.html
- https://www.educative.io/answers/what-is-the-difference-between-any-and-every-in-dart
Syntax highlighting
Tags: dart, flutter , syntax highlight, StatelessWidget
Displays 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:
- https://pub.dev/packages/flutter_highlight
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:
- https://stackoverflow.com/questions/27204728/is-there-a-built-in-function-to-copy-a-directory-in-dart
Colored Console
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:
- https://pub.dev/packages/colorize
Dart to JavaScript
Tags: dart, dart to javascript , dart export
Transpiles 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:
- https://pub.dev/packages/js