### Configure Dart Lint Rules Source: https://context7.com/dart-lang/core/llms.txt Example configuration for analysis_options.yaml to enable official Dart linting rules. ```yaml # analysis_options.yaml # Use recommended lints (includes core lints) include: package:lints/recommended.yaml # Or use only core lints # include: package:lints/core.yaml ``` -------------------------------- ### Initialize Logging with a Print Handler Source: https://github.com/dart-lang/core/blob/main/pkgs/logging/README.md Configure the root logger level to ALL and add a listener to print all log messages to the console. This is a basic setup for debugging. ```dart Logger.root.level = Level.ALL; Logger.root.onRecord.listen((record) { print('${record.level.name}: ${record.time}: ${record.message}'); }); ``` -------------------------------- ### Path Manipulation with Dart Path Package Source: https://context7.com/dart-lang/core/llms.txt Perform cross-platform path manipulations including joining, splitting, getting components (basename, dirname, extension), normalizing, and checking for absolute/relative paths. Import `package:path/path.dart` as `p`. ```dart import 'package:path/path.dart' as p; void main() { // Join path components print(p.join('directory', 'subdirectory', 'file.txt')); // POSIX: directory/subdirectory/file.txt // Windows: directory\subdirectory\file.txt // Get path components print(p.basename('/path/to/file.txt')); // file.txt print(p.basenameWithoutExtension('/path/to/file.txt')); // file print(p.dirname('/path/to/file.txt')); // /path/to print(p.extension('/path/to/file.txt')); // .txt // Split and join paths print(p.split('/path/to/file.txt')); // ['/', 'path', 'to', 'file.txt'] print(p.joinAll(['path', 'to', 'file.txt'])); // Normalize paths print(p.normalize('/path/./to/../file.txt')); // /path/file.txt print(p.canonicalize('/path/./to/../file.txt')); // resolves symlinks // Relative and absolute paths print(p.isAbsolute('/path/to/file')); // true print(p.isRelative('path/to/file')); // true print(p.relative('/root/path/to/file', from: '/root/path')); // to/file // Work with specific path styles var windowsContext = p.Context(style: p.Style.windows); print(windowsContext.join('C:', 'Users', 'file.txt')); // C:\Users\file.txt var urlContext = p.Context(style: p.Style.url); print(urlContext.join('https://example.com', 'path', 'page')); // https://example.com/path/page // Set extension print(p.setExtension('/path/to/file.txt', '.dart')); // /path/to/file.dart print(p.withoutExtension('/path/to/file.txt')); // /path/to/file } ``` -------------------------------- ### Initialize CommandRunner and Add Commands Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Sets up the main entry point for a command-line application using CommandRunner. It initializes the runner with an executable name and description, then adds custom commands. ```dart void main(List args) { var runner = CommandRunner("dgit", "A dart implementation of distributed version control.") ..addCommand(CommitCommand()) ..addCommand(StashCommand()) ..run(args); } ``` -------------------------------- ### Import the path library Source: https://github.com/dart-lang/core/blob/main/pkgs/path/README.md Recommended import pattern using a prefix to avoid naming conflicts. ```dart import 'package:path/path.dart' as p; ``` -------------------------------- ### Migrate general platform APIs from package:os_detect Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/migration-guide.md Switch from os_detect imports to the standard Platform.current API. ```dart import 'package:os_detect/os_detect.dart' as Platform; bool onAndroid = Platform.isAndroid; ``` ```dart import 'package:platform/platform.dart'; bool onAndroid = Platform.current.isAndroid; ``` -------------------------------- ### Import os_detect Package Source: https://github.com/dart-lang/core/blob/main/pkgs/os_detect/README.md Replace the import of `dart:io` with this to use the `os_detect` package for operating system detection. Ensure to adjust the import prefix if necessary. ```dart import 'package:os_detect/os_detect.dart' as os_detect; ``` -------------------------------- ### Define help text for options and flags Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use the help parameter to provide descriptions for options and flags. ```dart parser.addOption('mode', help: 'The compiler configuration', allowed: ['debug', 'release']); parser.addFlag('verbose', help: 'Show additional diagnostic info'); ``` -------------------------------- ### Migrate general platform APIs from package:platform 3.1 Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/migration-guide.md Replace LocalPlatform instantiation with the convenience Platform.current getter. ```dart import 'package:platform/platform.dart'; // version 3.1 bool onAndroid = LocalPlatform().isAndroid; ``` ```dart import 'package:platform/platform.dart'; // version 3.2 bool onAndroid = Platform.current.isAndroid; ``` -------------------------------- ### Define a Basic Option Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use `addOption()` to define a command-line option that accepts a string value. ```dart parser.addOption('name'); ``` -------------------------------- ### Define Command with Subcommands Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Illustrates how to create a command that has its own subcommands. A command with subcommands cannot implement its own run() method. ```dart class StashCommand extends Command { final String name = "stash"; final String description = "Stash changes in the working directory."; StashCommand() { addSubcommand(StashSaveCommand()); addSubcommand(StashListCommand()); } } ``` -------------------------------- ### Display usage information Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Access the usage getter on the parser instance to retrieve the generated help string. ```dart print(parser.usage); ``` -------------------------------- ### Implement command-based CLI with CommandRunner Source: https://context7.com/dart-lang/core/llms.txt Structures complex CLI tools with subcommands and automatic help generation. Requires 'args/command_runner.dart'. ```dart import 'package:args/command_runner.dart'; class CommitCommand extends Command { @override final name = 'commit'; @override final description = 'Record changes to the repository.'; CommitCommand() { argParser.addFlag('all', abbr: 'a', help: 'Commit all changed files'); argParser.addOption('message', abbr: 'm', help: 'Commit message', mandatory: true); } @override void run() { final all = argResults!.flag('all'); final message = argResults!.option('message'); print('Committing${all ? ' all files' : ''} with message: $message'); } } class StashCommand extends Command { @override final name = 'stash'; @override final description = 'Stash changes in the working directory.'; StashCommand() { addSubcommand(StashSaveCommand()); addSubcommand(StashListCommand()); } } class StashSaveCommand extends Command { @override final name = 'save'; @override final description = 'Save local modifications to a new stash.'; @override void run() => print('Stash saved!'); } class StashListCommand extends Command { @override final name = 'list'; @override final description = 'List all stashes.'; @override void run() => print('Listing stashes...'); } void main(List args) { var runner = CommandRunner('dgit', 'A dart implementation of version control.') ..addCommand(CommitCommand()) ..addCommand(StashCommand()); runner.run(args).catchError((error) { if (error is! UsageException) throw error; print(error); exit(64); }); } // Usage: dart run dgit.dart commit -a -m "Initial commit" // Usage: dart run dgit.dart stash save // Usage: dart run dgit.dart --help ``` -------------------------------- ### Generate and verify documentation Source: https://github.com/dart-lang/core/blob/main/pkgs/lints/tool/README.md Use the `gen_docs.dart` script to regenerate lint lists in the `README.md` file. The `--verify` flag can be used to check if the readme is up-to-date. This tool is also run by CI. ```shell dart run tool/gen_docs.dart ``` ```shell dart run tool/gen_docs.dart --verify ``` -------------------------------- ### Configure Hierarchical Logging in Dart Source: https://context7.com/dart-lang/core/llms.txt Sets up a root logger with listeners and demonstrates named loggers, log levels, and lazy message evaluation. ```dart import 'package:logging/logging.dart'; void main() { // Configure root logger Logger.root.level = Level.ALL; Logger.root.onRecord.listen((record) { print('${record.level.name}: ${record.time}: ${record.loggerName}: ${record.message}'); if (record.error != null) { print(' Error: ${record.error}'); print(' Stack: ${record.stackTrace}'); } }); // Create named loggers final log = Logger('MyApp'); final dbLog = Logger('MyApp.Database'); final apiLog = Logger('MyApp.API'); // Log at different levels log.finest('Extremely detailed debug info'); log.finer('More detailed debug info'); log.fine('Debug message'); log.config('Configuration message'); log.info('Informational message'); log.warning('Warning message'); log.severe('Error message'); log.shout('Critical message'); // Log with error and stack trace try { throw Exception('Something went wrong'); } catch (e, stackTrace) { log.severe('Operation failed', e, stackTrace); } // Lazy evaluation for expensive messages log.fine(() => 'Expensive computation: ${List.generate(1000, (i) => i).join(", ")}'); // Hierarchical logging hierarchicalLoggingEnabled = true; dbLog.level = Level.WARNING; // Only warnings and above for database dbLog.info('This will not be logged'); dbLog.warning('This will be logged'); // Listen for level changes Logger.root.onLevelChanged.listen((level) { print('Log level changed to: $level'); }); } ``` -------------------------------- ### Create a platform-specific path context Source: https://github.com/dart-lang/core/blob/main/pkgs/path/README.md Constructs a context to force path operations to follow a specific style regardless of the host platform. ```dart var context = p.Context(style: Style.windows); context.join('directory', 'file.txt'); ``` -------------------------------- ### Include Recommended Lint Set in analysis_options.yaml Source: https://github.com/dart-lang/core/blob/main/pkgs/lints/README.md Configure your project to use the recommended set of Dart lint rules by including this line in your `analysis_options.yaml` file. This enables a comprehensive set of checks for code quality and style. ```yaml include: package:lints/recommended.yaml ``` -------------------------------- ### Define a Custom Command Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Extends the Command class to create a new command for the application. This includes defining the command's name, description, and any specific arguments it accepts. ```dart class CommitCommand extends Command { // The [name] and [description] properties must be defined by every // subclass. final name = "commit"; final description = "Record changes to the repository."; CommitCommand() { // we can add command specific arguments here. // [argParser] is automatically created by the parent class. argParser.addFlag('all', abbr: 'a'); } // [run] may also return a Future. void run() { // [argResults] is set before [run()] is called and contains the flags/options // passed to this command. print(argResults.flag('all')); } } ``` -------------------------------- ### Update data files with license acceptance Source: https://github.com/dart-lang/core/blob/main/pkgs/characters/tool/README.txt Forces the update process to proceed after a license file change has been verified. ```bash dart tool.generate.dart -u -o --accept-license ``` -------------------------------- ### Update and optimize data files Source: https://github.com/dart-lang/core/blob/main/pkgs/characters/tool/README.txt Updates data files from the Unicode repository and optimizes table chunk sizes. ```bash dart tool.generate.dart -u -o ``` -------------------------------- ### Migrate native-only APIs from package:platform 3.1 Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/migration-guide.md Transition native-only properties to the NativePlatform class, guarded by an isNative check. ```dart import 'package:platform/platform.dart'; // version 3.1 String hostname = LocalPlatform().localHostname; ``` ```dart import 'package:platform/platform.dart'; // version 3.2 if (Platform.current.isNative) { String hostname = NativePlatform.current!.localHostname; print(hostname); } ``` -------------------------------- ### Join paths using top-level functions Source: https://github.com/dart-lang/core/blob/main/pkgs/path/README.md Joins path components using the current platform's directory separator. ```dart p.join('directory', 'file.txt'); ``` -------------------------------- ### Accessing Platform Information in Dart Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/README.md Use this snippet to determine the current runtime environment (native or web) and access relevant platform properties. Imports `package:platform/platform.dart`. ```dart import 'package:platform/platform.dart'; void main() { switch (Platform.current) { case Platform(:var nativePlatform?): // `nativePlatform` has `dart:io`'s `Platform` properties. print( 'Running on ${nativePlatform.operatingSystem} v.' '${nativePlatform.operatingSystemVersion}', ); case Platform(:var browserPlatform?): // `browserPlatform` has version information from `windows.userAgent`. print('Running on ${browserPlatform.userAgent}'); } } ``` -------------------------------- ### Define detailed help for allowed values Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use the allowedHelp parameter to provide descriptions for specific allowed values. ```dart parser.addOption('arch', help: 'The architecture to compile for', allowedHelp: { 'ia32': 'Intel x86', 'arm': 'ARM Holding 32-bit chip' }); ``` -------------------------------- ### Add an existing parser as a command Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Attaches a pre-configured ArgParser instance to a command. ```dart var parser = ArgParser(); var command = ArgParser(); parser.addCommand('commit', command); ``` -------------------------------- ### Regenerate project files Source: https://github.com/dart-lang/core/blob/main/pkgs/characters/tool/README.txt Executes the generation script to update project files. ```bash dart tool/generate.dart ``` -------------------------------- ### Handle CommandRunner Exceptions Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Shows how to catch and handle UsageException thrown by CommandRunner for invalid arguments or command processing errors. It prints the error and exits with a specific code. ```dart runner.run(arguments).catchError((error) { if (error is! UsageException) throw error; print(error); exit(64); // Exit code 64 indicates a usage error. }); ``` -------------------------------- ### Add Global Arguments to CommandRunner Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Demonstrates how to add global arguments to the CommandRunner that apply to all commands. These are defined by accessing the runner's argParser. ```dart var runner = CommandRunner('dgit', "A dart implementation of distributed version control."); // add global flag runner.argParser.addFlag('verbose', abbr: 'v', help: 'increase logging'); ``` -------------------------------- ### Add and Run Lints Source: https://context7.com/dart-lang/core/llms.txt Add the 'dev:lints' package to your project using Dart Pub. Run the Dart analyzer to check for linting issues. ```bash # Add lints to your project dart pub add dev:lints # Run analyzer dart analyze ``` -------------------------------- ### Resolve command-specific options Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Shows how the parser resolves options based on their position relative to the command. ```dart var parser = ArgParser(); parser.addFlag('all', abbr: 'a'); var command = parser.addCommand('commit'); command.addFlag('all', abbr: 'a'); var results = parser.parse(['commit', '-a']); print(results.command['all']); // true ``` -------------------------------- ### Parse command-line arguments with ArgParser Source: https://context7.com/dart-lang/core/llms.txt Defines flags, options, and multi-value options for CLI applications. Requires the 'args' package. ```dart import 'package:args/args.dart'; void main(List arguments) { var parser = ArgParser() ..addFlag('verbose', abbr: 'v', help: 'Enable verbose output', defaultsTo: false) ..addOption('output', abbr: 'o', help: 'Output file path', valueHelp: 'path') ..addOption('mode', allowed: ['debug', 'release'], defaultsTo: 'debug') ..addMultiOption('include', abbr: 'I', help: 'Include directories'); try { var results = parser.parse(arguments); print('Verbose: ${results.flag('verbose')}'); // true or false print('Output: ${results.option('output')}'); // e.g., '/tmp/out.txt' print('Mode: ${results.option('mode')}'); // 'debug' or 'release' print('Includes: ${results.multiOption('include')}'); // ['dir1', 'dir2'] print('Remaining args: ${results.rest}'); // positional arguments // Display usage help print(parser.usage); } on ArgParserException catch (e) { print('Error: ${e.message}'); print(parser.usage); } } // Usage: dart run myapp.dart -v --output=/tmp/out.txt --mode=release -I dir1 -I dir2 file.txt ``` -------------------------------- ### Define value help for options Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use the valueHelp parameter to specify a placeholder name for non-flag option values. ```dart parser.addOption('out', help: 'The output path', valueHelp: 'path', allowed: ['debug', 'release']); ``` -------------------------------- ### Migrate general platform APIs from dart:io Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/migration-guide.md Replace static Platform members with Platform.current to ensure cross-platform compatibility. ```dart import 'dart:io'; bool onAndroid = Platform.isAndroid; ``` ```dart import 'package:platform/platform.dart'; bool onAndroid = Platform.current.isAndroid; ``` -------------------------------- ### Configure Hierarchical Logging Source: https://github.com/dart-lang/core/blob/main/pkgs/logging/README.md Enable hierarchical logging and configure individual loggers with specific levels and listeners. Loggers inherit settings from their ancestors if not explicitly set. ```dart hierarchicalLoggingEnabled = true; Logger.root.level = Level.WARNING; Logger.root.onRecord.listen((record) { print('[ROOT][WARNING+] ${record.message}'); }); final log1 = Logger('FINE+'); log1.level = Level.FINE; log1.onRecord.listen((record) { print('[LOG1][FINE+] ${record.message}'); }); // log2 inherits LEVEL value of WARNING from `Logger.root` final log2 = Logger('WARNING+'); log2.onRecord.listen((record) { print('[LOG2][WARNING+] ${record.message}'); }); // Will NOT print because FINER is too low level for `Logger.root`. log1.finer('LOG_01 FINER (X)'); // Will print twice ([LOG1] & [ROOT]) log1.fine('LOG_01 FINE (√√)'); // Will print ONCE because `log1` only uses root listener. log1.warning('LOG_01 WARNING (√)'); // Will never print because FINE is too low level. log2.fine('LOG_02 FINE (X)'); // Will print twice ([LOG2] & [ROOT]) because warning is sufficient for all // loggers' levels. log2.warning('LOG_02 WARNING (√√)'); // Will never print because `info` is filtered by `Logger.root.level` of // `Level.WARNING`. log2.info('INFO (X)'); ``` -------------------------------- ### Define options for a command Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Adds flags or options specifically to a command parser. ```dart command.addFlag('all', abbr: 'a'); ``` -------------------------------- ### Run lib validation tool Source: https://github.com/dart-lang/core/blob/main/pkgs/lints/tool/README.md Execute the `validate_lib.dart` script to ensure no `.dart` source files are committed into the `lib/` directory. This is typically run automatically by CI but can be executed manually. ```shell dart run tool/validate_lib.dart ``` -------------------------------- ### Detect Platform Environment Source: https://context7.com/dart-lang/core/llms.txt Uses the platform package to distinguish between native and browser environments and access platform-specific properties. ```dart import 'package:platform/platform.dart'; void main() { switch (Platform.current) { case Platform(:var nativePlatform?): // Running on native platform (VM, AOT) print('Operating System: ${nativePlatform.operatingSystem}'); print('OS Version: ${nativePlatform.operatingSystemVersion}'); print('Number of processors: ${nativePlatform.numberOfProcessors}'); print('Locale: ${nativePlatform.localeName}'); print('Hostname: ${nativePlatform.localHostname}'); // Check specific platforms if (nativePlatform.isLinux) print('Running on Linux'); if (nativePlatform.isMacOS) print('Running on macOS'); if (nativePlatform.isWindows) print('Running on Windows'); if (nativePlatform.isAndroid) print('Running on Android'); if (nativePlatform.isIOS) print('Running on iOS'); // Environment variables var home = nativePlatform.environment['HOME']; print('Home directory: $home'); case Platform(:var browserPlatform?): // Running in browser print('User Agent: ${browserPlatform.userAgent}'); } } ``` -------------------------------- ### Define an option with ArgParser Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Configures a named option with a short abbreviation. ```dart parser.addOption('name', abbr: 'n'); ``` -------------------------------- ### Hashing Functions with Dart Crypto Package Source: https://context7.com/dart-lang/core/llms.txt Implement cryptographic hash functions like SHA-1, SHA-256, SHA-512, and MD5 using the `crypto` package. Supports HMAC and chunked hashing for large data. Ensure `dart:convert` and `package:crypto/crypto.dart` are imported. ```dart import 'dart:convert'; import 'package:crypto/crypto.dart'; void main() { var message = 'Hello, World!'; var bytes = utf8.encode(message); // SHA-1 hash var sha1Digest = sha1.convert(bytes); print('SHA-1: $sha1Digest'); // Output: SHA-1: 0a0a9f2a6772942557ab5355d76af442f8f65e01 // SHA-256 hash var sha256Digest = sha256.convert(bytes); print('SHA-256: $sha256Digest'); print('SHA-256 bytes: ${sha256Digest.bytes}'); // SHA-512 hash var sha512Digest = sha512.convert(bytes); print('SHA-512: $sha512Digest'); // MD5 hash (not recommended for security) var md5Digest = md5.convert(bytes); print('MD5: $md5Digest'); // HMAC with SHA-256 var key = utf8.encode('secret-key'); var hmacSha256 = Hmac(sha256, key); var hmacDigest = hmacSha256.convert(bytes); print('HMAC-SHA256: $hmacDigest'); // Chunked hashing for large data var output = AccumulatorSink(); var input = sha256.startChunkedConversion(output); input.add(utf8.encode('First chunk')); input.add(utf8.encode('Second chunk')); input.add(utf8.encode('Third chunk')); input.close(); print('Chunked SHA-256: ${output.events.single}'); } ``` -------------------------------- ### Add a command to a parser Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Registers a new command and retrieves its associated parser. ```dart var parser = ArgParser(); var command = parser.addCommand('commit'); ``` -------------------------------- ### Include Core Lint Set in analysis_options.yaml Source: https://github.com/dart-lang/core/blob/main/pkgs/lints/README.md Configure your project to use the core set of Dart lint rules by including this line in your `analysis_options.yaml` file. This focuses on critical issues likely to cause problems during runtime or consumption. ```yaml include: package:lints/core.yaml ``` -------------------------------- ### Generate HMAC in Dart Source: https://github.com/dart-lang/core/blob/main/pkgs/crypto/README.md Initialize an Hmac instance with a hash function and a secret key, then use the convert method to generate the HMAC digest. ```dart import 'dart:convert'; import 'package:crypto/crypto.dart'; void main() { var key = utf8.encode('p@ssw0rd'); var bytes = utf8.encode("foobar"); var hmacSha256 = Hmac(sha256, key); // HMAC-SHA256 var digest = hmacSha256.convert(bytes); print("HMAC digest as bytes: ${digest.bytes}"); print("HMAC digest as hex string: $digest"); } ``` -------------------------------- ### Importing the typed_data package Source: https://github.com/dart-lang/core/blob/main/pkgs/typed_data/README.md Include this import statement to access the utility functions and classes provided by the package. ```dart import 'package:typed_data/typed_data.dart'; ``` -------------------------------- ### Access Parsed Options and Flags Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Retrieve option values using `results.option()` and flag values using `results.flag()`. Default values are returned if options are not provided. ```dart var parser = ArgParser(); parser.addOption('mode'); parser.addFlag('verbose', defaultsTo: true); var results = parser.parse(['--mode', 'debug', 'something', 'else']); print(results.option('mode')); // debug print(results.flag('verbose')); // true ``` -------------------------------- ### Configure Lints and Analyzer Rules Source: https://context7.com/dart-lang/core/llms.txt Customize linter rules by disabling or enabling specific checks. Configure the analyzer to exclude files and treat specific error types. ```yaml linter: rules: # Disable a rule avoid_print: false # Enable additional rules always_declare_return_types: true prefer_single_quotes: true sort_constructors_first: true analyzer: exclude: - "**/*.g.dart" - "build/**" errors: # Treat info as warning todo: warning # Ignore specific rules unused_import: ignore ``` -------------------------------- ### Hash chunked input in Dart Source: https://github.com/dart-lang/core/blob/main/pkgs/crypto/README.md Use startChunkedConversion to process data in multiple parts, requiring an AccumulatorSink from the convert package to collect the final digest. ```dart import 'dart:convert'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; void main() { var firstChunk = utf8.encode("foo"); var secondChunk = utf8.encode("bar"); var output = AccumulatorSink(); var input = sha1.startChunkedConversion(output); input.add(firstChunk); input.add(secondChunk); // call `add` for every chunk of input data input.close(); var digest = output.events.single; print("Digest as bytes: ${digest.bytes}"); print("Digest as hex string: $digest"); } ``` -------------------------------- ### Create a Named Logger Source: https://github.com/dart-lang/core/blob/main/pkgs/logging/README.md Instantiate a Logger with a specific name to identify the source of log messages. This is useful for organizing logs from different parts of an application. ```dart final log = Logger('MyClassName'); ``` -------------------------------- ### Override Operating System Detection Source: https://github.com/dart-lang/core/blob/main/pkgs/os_detect/README.md Use `overrideOperatingSystem` from `package:os_detect/override.dart` to run code within a zone where the operating system and version are temporarily set to specified values. This is useful for testing. ```dart import 'package:os_detect/override.dart'; void main() { overrideOperatingSystem( operatingSystem: 'browser', operatingSystemVersion: '1.0.0', run: () { // Code to run in the overridden environment print(os_detect.operatingSystem); print(os_detect.operatingSystemVersion); }, ); } ``` -------------------------------- ### Growable Typed Data Buffers with typed_data Source: https://context7.com/dart-lang/core/llms.txt Utilize growable typed data buffers for efficient storage and manipulation of byte, float, and integer data. Automatically grows beyond initial capacity. ```dart import 'package:typed_data/typed_data.dart'; void main() { // Growable Uint8 buffer var bytes = Uint8Buffer(); bytes.add(0x48); // 'H' bytes.add(0x69); // 'i' bytes.addAll([0x21, 0x21]); // '!!' print('Bytes: $bytes'); // [72, 105, 33, 33] print('As string: ${String.fromCharCodes(bytes)}'); // Hi!! // Float64 buffer for numeric data var floats = Float64Buffer(); floats.addAll([1.5, 2.7, 3.14159]); print('Floats: $floats'); print('Sum: ${floats.reduce((a, b) => a + b)}'); // Int32 buffer var ints = Int32Buffer(10); // Initial capacity of 10 for (var i = 0; i < 20; i++) { ints.add(i * i); // Auto-grows beyond initial capacity } print('Squares: $ints'); // Convert to typed list var fixedList = bytes.buffer.asUint8List(); print('Fixed list type: ${fixedList.runtimeType}'); } ``` -------------------------------- ### Define Option with Abbreviation Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Specify a single-character abbreviation for an option or flag using the `abbr` parameter. ```dart parser.addOption('mode', abbr: 'm'); parser.addFlag('verbose', abbr: 'v'); ``` -------------------------------- ### PriorityQueue for Ordered Elements Source: https://context7.com/dart-lang/core/llms.txt Implement a priority queue using PriorityQueue for efficient insertion and removal of elements based on their priority. Supports custom comparison logic for non-comparable types. ```dart import 'package:collection/collection.dart'; class Task { final String name; final int priority; Task(this.name, this.priority); @override String toString() => '$name (priority: $priority)'; } void main() { // Simple priority queue with comparable elements var numbers = PriorityQueue(); numbers.addAll([5, 1, 8, 3, 9, 2]); while (numbers.isNotEmpty) { print(numbers.removeFirst()); // 1, 2, 3, 5, 8, 9 } // Custom comparison function (lower priority number = higher priority) var tasks = PriorityQueue((a, b) => a.priority.compareTo(b.priority)); tasks.add(Task('Low priority task', 10)); tasks.add(Task('High priority task', 1)); tasks.add(Task('Medium priority task', 5)); print('First task: ${tasks.first}'); // High priority task (priority: 1) while (tasks.isNotEmpty) { print('Processing: ${tasks.removeFirst()}'); } // Create from existing elements var fromList = PriorityQueue.of( [Task('A', 3), Task('B', 1), Task('C', 2)], (a, b) => a.priority.compareTo(b.priority), ); print('Highest priority: ${fromList.first}'); // B (priority: 1) } ``` -------------------------------- ### Parse comma-separated multi-options Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Demonstrates the default behavior of splitting comma-separated values in multi-options. ```dart var parser = ArgParser(); parser.addMultiOption('mode'); var results = parser.parse(['--mode', 'on,off']); print(results.multiOption('mode')); // prints '[on, off]' ``` -------------------------------- ### Define a flag with ArgParser Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Configures a boolean flag with a short abbreviation. ```dart parser.addFlag('name', abbr: 'n'); ``` -------------------------------- ### Parse Command-Line Arguments Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use `ArgParser.parse()` to process a list of string arguments. The result is an `ArgResults` object. ```dart var results = parser.parse(['some', 'command', 'line', 'args']); ``` -------------------------------- ### Iterable Extensions in Dart Collection Source: https://context7.com/dart-lang/core/llms.txt Utilize extension methods for common iterable operations like finding first/last elements, grouping, sorting, min/max, binary search, slicing, and flattening. Ensure the `collection` package is imported. ```dart import 'package:collection/collection.dart'; void main() { var numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]; // First/last or null (no exception if empty) print(numbers.firstOrNull); // 3 print([].firstOrNull); // null print(numbers.lastOrNull); // 3 // First/last where or null print(numbers.firstWhereOrNull((n) => n > 10)); // null // Group by var grouped = numbers.groupListsBy((n) => n % 2 == 0 ? 'even' : 'odd'); print(grouped); // {odd: [3, 1, 1, 5, 9, 5, 3], even: [4, 2, 6]} // Sorted copy (doesn't modify original) var sorted = numbers.sorted(); print(sorted); // [1, 1, 2, 3, 3, 4, 5, 5, 6, 9] // Sort by property var words = ['apple', 'pie', 'a', 'banana']; var byLength = words.sortedBy((w) => w.length); print(byLength); // [a, pie, apple, banana] // Min/max print(numbers.min); // 1 print(numbers.max); // 9 // Binary search (on sorted list) var sortedList = [1, 2, 3, 4, 5, 6, 7, 8, 9]; print(sortedList.binarySearch(5)); // 4 (index) // Slices var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (var slice in items.slices(3)) { print(slice); // [1, 2, 3], [4, 5, 6], [7, 8, 9], [10] } // Flatten nested iterables var nested = [[1, 2], [3, 4], [5]]; print(nested.flattened.toList()); // [1, 2, 3, 4, 5] } ``` -------------------------------- ### Define Option with Callback Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Associate a function with an option or flag that will be invoked with the option's value during parsing. ```dart parser.addOption('mode', callback: (mode) => print('Got mode $mode')); parser.addFlag('verbose', callback: (verbose) { if (verbose) print('Verbose'); }); ``` -------------------------------- ### Memoize and cache async results Source: https://context7.com/dart-lang/core/llms.txt AsyncMemoizer ensures an operation runs only once, while AsyncCache provides time-based caching for expensive async computations. ```dart import 'package:async/async.dart'; class DatabaseConnection { final _connectionMemoizer = AsyncMemoizer(); // Connection is established only once, even if called multiple times Future connect() => _connectionMemoizer.runOnce(() async { print('Establishing connection...'); await Future.delayed(Duration(seconds: 2)); return 'Connected to database'; }); } class ExpensiveDataFetcher { // Cache results for 5 minutes final _cache = AsyncCache>(Duration(minutes: 5)); Future> fetchData() => _cache.fetch(() async { print('Fetching data from API...'); await Future.delayed(Duration(seconds: 1)); return {'timestamp': DateTime.now().toIso8601String(), 'data': 'cached'}; }); void invalidateCache() => _cache.invalidate(); } Future main() async { var db = DatabaseConnection(); // These all return the same connection var results = await Future.wait([ db.connect(), db.connect(), db.connect(), ]); print(results); // All three are the same result var fetcher = ExpensiveDataFetcher(); print(await fetcher.fetchData()); // Fetches from API print(await fetcher.fetchData()); // Returns cached result fetcher.invalidateCache(); print(await fetcher.fetchData()); // Fetches again } ``` -------------------------------- ### Parse command results Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Retrieves the command name and its specific options from parsed results. ```dart var results = parser.parse(['commit', '-a']); print(results.command.name); // "commit" print(results.command['all']); // true ``` -------------------------------- ### Log Debug and Error Messages with Async Handling Source: https://github.com/dart-lang/core/blob/main/pkgs/logging/README.md Log a fine-grained message upon successful completion of an asynchronous operation and an error message with stack trace if an error occurs. Ensure `doSomethingAsync` and `processResult` are defined elsewhere. ```dart var future = doSomethingAsync().then((result) { log.fine('Got the result: $result'); processResult(result); }).catchError((e, stackTrace) => log.severe('Oh noes!', e, stackTrace)); ``` -------------------------------- ### Migrate native-only APIs from dart:io Source: https://github.com/dart-lang/core/blob/main/pkgs/platform/migration-guide.md Use Platform.current.isNative to guard access to native-only APIs via NativePlatform.current. ```dart import 'dart:io'; String hostname = Platform.localHostname; ``` ```dart import 'package:platform/platform.dart'; if (Platform.current.isNative) { String hostname = NativePlatform.current!.localHostname; } ``` -------------------------------- ### Custom Equality Comparisons with Equality Classes Source: https://context7.com/dart-lang/core/llms.txt Utilize Equality classes for deep, set, map, unordered iterable, and case-insensitive string comparisons. These can be integrated into HashMaps for custom key equality. ```dart import 'package:collection/collection.dart'; void main() { // Deep equality for lists var list1 = [1, 2, [3, 4]]; var list2 = [1, 2, [3, 4]]; print(list1 == list2); // false (different objects) print(const DeepCollectionEquality().equals(list1, list2)); // true // Set equality (ignores order) var setEquality = const SetEquality(); print(setEquality.equals({1, 2, 3}, {3, 2, 1})); // true // Map equality var mapEquality = const MapEquality(); print(mapEquality.equals({'a': 1, 'b': 2}, {'b': 2, 'a': 1})); // true // Unordered list equality (like set but allows duplicates) var unorderedEquality = const UnorderedIterableEquality(); print(unorderedEquality.equals([1, 2, 2, 3], [3, 2, 1, 2])); // true // Case-insensitive string equality var caseInsensitive = const CaseInsensitiveEquality(); print(caseInsensitive.equals('Hello', 'HELLO')); // true // Use equality in a HashMap var caseInsensitiveMap = HashMap( equals: caseInsensitive.equals, hashCode: caseInsensitive.hash, ); caseInsensitiveMap['Key'] = 1; print(caseInsensitiveMap['KEY']); // 1 } ``` -------------------------------- ### Consume Stream Event-by-Event with StreamQueue Source: https://context7.com/dart-lang/core/llms.txt Use StreamQueue for explicit control over stream consumption, allowing peeking, taking, and skipping events. Ensure to cancel the queue when done to clean up resources. ```dart import 'package:async/async.dart'; Future main() async { var events = StreamQueue(Stream.fromIterable([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); // Get next event var first = await events.next; print('First: $first'); // 1 // Peek without consuming var peeked = await events.peek; print('Peeked: $peeked'); // 2 var stillThere = await events.next; print('Still there: $stillThere'); // 2 // Take multiple events var batch = await events.take(3); print('Batch: $batch'); // [3, 4, 5] // Skip events await events.skip(2); // Skips 6 and 7 // Check if more events exist if (await events.hasNext) { var remaining = await events.rest.toList(); print('Remaining: $remaining'); // [8, 9, 10] } // Cancel and clean up await events.cancel(); } ``` -------------------------------- ### Extracting tags with String vs Characters Source: https://github.com/dart-lang/core/blob/main/pkgs/characters/README.md Comparison between using standard String indices and CharacterRange operations to extract content between tags. ```dart // Using String indices. String? firstTagString(String source) { var start = source.indexOf('<') + 1; if (start > 0) { var end = source.indexOf('>', start); if (end >= 0) { return source.substring(start, end); } } return null; } // Using CharacterRange operations. Characters? firstTagCharacters(Characters source) { var range = source.findFirst('<'.characters); if (range != null && range.moveUntil('>'.characters)) { return range.currentCharacters; } return null; } ``` -------------------------------- ### Define Option with Default Value Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Set a default value for an option or flag using the `defaultsTo` parameter. The type must match the option (String for options, bool for flags). ```dart parser.addOption('mode', defaultsTo: 'debug'); parser.addFlag('verbose', defaultsTo: false); ``` -------------------------------- ### Define Option with Allowed Values Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Restrict the acceptable values for a non-flag option using the `allowed` parameter. An `ArgParserException` is thrown for invalid values. ```dart parser.addOption('mode', allowed: ['debug', 'release']); ``` -------------------------------- ### Fixed-Width Integers with fixnum Source: https://context7.com/dart-lang/core/llms.txt Use 32-bit and 64-bit signed fixed-width integers that function consistently across Dart VM and JavaScript. Supports arithmetic operations and parsing from strings. ```dart import 'package:fixnum/fixnum.dart'; void main() { // 64-bit integers that work correctly in JavaScript var big = Int64(9223372036854775807); // Max int64 print('Max Int64: $big'); // Arithmetic operations var a = Int64(1000000000000); var b = Int64(2000000000000); print('Sum: ${a + b}'); print('Product: ${a * Int64(2)}'); print('Division: ${b ~/ a}'); // Parse from string var fromString = Int64.parseRadix('7FFFFFFFFFFFFFFF', 16); print('From hex: $fromString'); // Convert to/from bytes var value = Int64(0x0102030405060708); var bytes = [ value.shiftRightUnsigned(56).toInt() & 0xFF, value.shiftRightUnsigned(48).toInt() & 0xFF, value.shiftRightUnsigned(40).toInt() & 0xFF, value.shiftRightUnsigned(32).toInt() & 0xFF, value.shiftRightUnsigned(24).toInt() & 0xFF, value.shiftRightUnsigned(16).toInt() & 0xFF, value.shiftRightUnsigned(8).toInt() & 0xFF, value.toInt() & 0xFF, ]; print('Bytes: $bytes'); // 32-bit integers var int32 = Int32(2147483647); // Max int32 print('Max Int32: $int32'); print('Overflow: ${int32 + Int32(1)}'); // Wraps around } ``` -------------------------------- ### Listen for Log Level Changes Source: https://github.com/dart-lang/core/blob/main/pkgs/logging/README.md Add a listener to the root logger's onLevelChanged stream to be notified when the log level is updated. This can be useful for dynamic logging configurations. ```dart Logger.root.onLevelChanged.listen((level) { print('The new log level is $level'); }); ``` -------------------------------- ### Add Lints Package to Dependencies Source: https://github.com/dart-lang/core/blob/main/pkgs/lints/README.md Use this command to add the `lints` package as a development dependency to your Dart project. This is typically done for existing projects or when you need to manage lint settings manually. ```bash dart pub add dev:lints ``` -------------------------------- ### Define Map Equality Source: https://github.com/dart-lang/core/blob/main/pkgs/collection/README.md Creates an equality instance for maps where keys are compared by identity and values are compared as lists with standard equality. ```dart const MapEquality(IdentityEquality(), ListEquality()); ``` -------------------------------- ### Override default option values Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Demonstrates that subsequent occurrences of an option override previous values. ```dart var parser = ArgParser(); parser.addOption('mode'); var results = parser.parse(['--mode', 'on', '--mode', 'off']); print(results.option('mode')); // prints 'off' ``` -------------------------------- ### Define Mandatory Option Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Mark an option as mandatory using the `mandatory` parameter. An `ArgumentError` is thrown if it's not provided. ```dart parser.addOption('mode', mandatory: true); ``` -------------------------------- ### Define a Basic Flag Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Use `addFlag()` to define a boolean flag that can be set or unset. ```dart parser.addFlag('name'); ``` -------------------------------- ### Collapse multiple flag abbreviations Source: https://github.com/dart-lang/core/blob/main/pkgs/args/README.md Defines multiple flags that can be invoked together in a single argument string. ```dart parser ..addFlag('verbose', abbr: 'v') ..addFlag('french', abbr: 'f') ..addFlag('iambic-pentameter', abbr: 'i'); ```