Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SNNafi/ed9d4ee98ace0d5b8ec9184f6c468d39 to your computer and use it in GitHub Desktop.
Save SNNafi/ed9d4ee98ace0d5b8ec9184f6c468d39 to your computer and use it in GitHub Desktop.
Simulate varargs in Dart and create a logs function with varargs
import 'dart:developer' as dev;
import 'package:flutter/foundation.dart';

typedef OnCall = dynamic Function(
    List<dynamic> args, Map<Symbol, dynamic> kwargs);

class VariadicFunction {
  VariadicFunction(this._onCall);

  final OnCall _onCall;

  @override
  noSuchMethod(Invocation invocation) {
    if (!invocation.isMethod) {
      super.noSuchMethod(invocation);
    }
    final arguments = invocation.positionalArguments;
    final kwArguments = invocation.namedArguments;
    return _onCall(arguments, kwArguments);
  }
}

final logs = VariadicFunction((args, kwargs) {
  if (!kDebugMode) return;
  final positional = args.isNotEmpty ? args.join(' ') : '';
  final named = kwargs.isEmpty
      ? ''
      : kwargs
          .map((key, value) => MapEntry(
              [
                key.toString().replaceAll('Symbol("', "").replaceAll('")', ''),
                ': ',
                value
              ].join(''),
              ''))
          .keys
          .join(' ');

  dev.log(
    [positional, named].join(' '),
    time: DateTime.now(),
  );
}) as dynamic;
@SNNafi
Copy link
Author

SNNafi commented Feb 13, 2024

We can use this like logs(8, 9, "hello", [8, 9, 9], log: 67, other: 76); It will print on the console,

[log] 8 9 hello [8, 9, 9] log: 67 other: 76

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment