Skip to content

Instantly share code, notes, and snippets.

@javacommons
Last active April 26, 2025 15:16
Show Gist options
  • Save javacommons/2446ce18252aa7623607f0ccd2aaf570 to your computer and use it in GitHub Desktop.
Save javacommons/2446ce18252aa7623607f0ccd2aaf570 to your computer and use it in GitHub Desktop.
import 'package:dynamic_function/dynamic_function.dart';
import 'dart:convert' as convert;
// equivalent to:
// void echo(dynamic x, [String? title], {bool asJson});
final dynamic echo = DynamicFunction((
List<dynamic> positional,
Map<Symbol, dynamic> named,
) {
if (positional.length < 1 || positional.length > 2) {
throw '${positional.length} arguments supplied to echo()';
}
dynamic x = positional[0];
String? title = positional.length == 2 ? positional[1] as String : null;
checkNamed(named, ['asJson']);
bool asJson =
named[Symbol('asJson')] == null ? false : named[Symbol('asJson')] as bool;
String json = (x is String) ? '`${x}`' : '${x}';
if (asJson) {
json = convert.jsonEncode(x);
}
if (title == null) {
print(json);
} else {
print('${title} ==> ${json}');
}
return null;
});
void main() {
final x = [11, null, 'abc'];
echo(x); // (1)
echo(x, 'x'); // (2)
echo(x, asJson: true); // (3)
echo(x, 'x', asJson: true); // (4)
//echo(); // 0 arguments supplied to echo()
//echo(x, 'x', 777); // 3 arguments supplied to echo()
}
/*
[Result]
[11, null, abc] // (1)
x ==> [11, null, abc] // (2)
[11,null,"abc"] // (3)
x ==> [11,null,"abc"] // (4)
*/
name: my_app
description: A sample command-line application
version: 0.0.1
publish_to: none
environment:
sdk: ^3.7.2
dependencies:
dynamic_function: ^2025.426.2037
dev_dependencies:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment