### Run Full Test Suite Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Execute the complete suite of tests for the project. Ensure Dart 3.10+ is installed. ```bash dart test ``` -------------------------------- ### Release Script Usage Examples Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/scripts/README.md Demonstrates various ways to invoke the release script, from fully interactive to non-interactive and dry-run modes. The script handles version bumping, changelog updates, tagging, and pushing. ```bash scripts/release.sh # fully interactive scripts/release.sh patch # bump type set, confirm on TTY scripts/release.sh patch --yes # non-interactive (CI-style) scripts/release.sh --dry-run # full preflight + plan, no side effects scripts/release.sh minor -m "Big new feature" # annotated tag with this message ``` -------------------------------- ### View Binding to ViewModel Callback Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Example of how a view binds to a ViewModel's callback method, explicitly using named parameters for clarity. ```dart onChanged: (value) => viewModel.onAcceptAnyTwoXxToggled(value: value), ``` -------------------------------- ### Fallback to GET Method for Probes Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Configure probes to fall back to using the GET method if the HEAD method fails. This ensures reachability checks work even with servers that don't support HEAD requests. ```dart final connectivity = BetterInternetConnectivityChecker( probeFactory: HttpProbe.get, ); final status = await connectivity.check(); print('Status using GET fallback: $status'); ``` -------------------------------- ### Implement a custom ConnectivityObserver Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Subclass ConnectivityObserver to create a custom observer for specific connectivity events. This example logs status changes and external trigger errors using a provided AppLogger. ```dart final class _AppConnectivityObserver extends ConnectivityObserver { const _AppConnectivityObserver(this._logger); final AppLogger _logger; @override void onStatusChangeEmitted(InternetStatus? previous, InternetStatus next) => _logger.info('connectivity: ${previous ?? ''} -> $next'); @override void onExternalTriggerError(Object error, StackTrace stackTrace) => _logger.error('connectivity trigger failed', error, stackTrace); } attachObserver(checker.events, _AppConnectivityObserver(appLogger)); ``` -------------------------------- ### ViewModel Callback for Toggled Event Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Example of a ViewModel method named from the view's perspective for a toggled event, with named parameter usage for boolean values. ```dart void onAcceptAnyTwoXxToggled({required bool value}) => _shouldAcceptAnyTwoXxNotifier.value = value; ``` -------------------------------- ### Fallback to HTTP GET Probe Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Use HttpProbe.get() if some endpoints reject HEAD requests or strip caching headers. The response body is drained but not buffered. ```dart final checker = InternetConnection( probe: HttpProbe.get(), ); ``` -------------------------------- ### Local Variable Type Suffix Example Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Use type suffixes for local variables to improve readability, especially when IDE inlay hints are not available. This helps readers quickly understand the variable's type without needing to trace its assignment. ```dart final probeResults = await targets.map(probe.probe).wait; final worstDuration = probeResults .map((result) => result.responseTime) .reduce((a, b) => a > b ? a : b); ``` ```dart final results = await targets.map(probe.probe).wait; final worst = results.map((r) => r.responseTime).reduce((a, b) => a > b ? a : b); ``` -------------------------------- ### Benchmark Running Commands Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md These commands are used to build scenario executables, run benchmarks, render reports, and compare benchmark results. Ensure you are in the benchmark/python/ directory and have activated the virtual environment. ```bash # 1. Build all scenario .dart files to AOT exes. # Parallelised across cores; cap with --workers if you're memory-bound. uv run python run.py build ``` ```bash # 2. Run all scenarios + micro-benches, default N=10 iterations. # Each scenario binary accepts --iterations and emits N records from one # subprocess invocation — saves N-1 process startups per scenario. uv run python run.py run --iterations 10 --out=../results-local/ ``` ```bash # 3. Render report (PNGs + SUMMARY.md). Default output is ../reports/ # (committed). Pass --out for ad-hoc local snapshots. uv run python run.py report ../results-local/current/aggregated.json ``` ```bash # 4. Compare two runs - Mann-Whitney significance + paired charts + forest. # Same default output dir (../reports/) with compare_*.png + COMPARE.md # filenames. Pass --out for ad-hoc local snapshots. uv run python run.py compare ../results-local/baseline/aggregated.json \ ../results-local/current/aggregated.json ``` -------------------------------- ### Create AI Agent Discovery Symlinks Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Run these commands from the repo root to set up symlinks for AI agents like Claude Code, Codex, Cursor, and Copilot. This allows agents to discover guidance files without duplicating them. ```bash ln -s .ai/AGENTS.md AGENTS.md ln -s .ai/CLAUDE.md CLAUDE.md ln -s .ai/AGENTS.md example/AGENTS.md ln -s .ai/AGENTS.md benchmark/python/AGENTS.md ``` -------------------------------- ### Per-Contributor Benchmark Workflow Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md Steps to capture baseline performance, apply changes, capture post-change performance, and compare the two results locally. ```bash cd benchmark/python # 1. Capture YOUR baseline on a clean working tree. uv run python run.py run --iterations 10 --out ../results-local/baseline/ # 2. Make your change. Commit it on a branch. # 3. Capture a new run with the change applied. uv run python run.py run --iterations 10 --out ../results-local/after/ # 4. Compare YOUR baseline to YOUR after-run (same machine, same SDK). uv run python run.py compare \ ../results-local/baseline/aggregated.json \ ../results-local/after/aggregated.json ``` -------------------------------- ### Linting Python Code Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md Run these commands to format and lint the Python code in the benchmark directory. Configuration is managed in pyproject.toml. ```bash cd benchmark/python uv run ruff format . uv run ruff check . ``` -------------------------------- ### Write a Custom Connectivity Probe Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Implement a custom probe by extending the `ConnectivityProbe` class. This allows for unique checking mechanisms beyond standard HTTP probes. ```dart import 'package:better_internet_connectivity_checker/better_internet_connectivity_checker.dart'; class MyCustomProbe extends ConnectivityProbe { @override Future probe({Duration? timeout}) async { // Your custom probing logic here return ProbeResult.reachable(Duration.zero); } } final connectivity = BetterInternetConnectivityChecker( probeFactory: (_) => MyCustomProbe(), ); final status = await connectivity.check(); print('Status with custom probe: $status'); ``` -------------------------------- ### Check Code Formatting Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Verify that the code adheres to the project's formatting standards. This command checks for changes without applying them. ```bash dart format --output=none --set-exit-if-changed . ``` -------------------------------- ### Prefer Named Constructors for Compile-Time Known URIs Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Use `Uri.https` or `Uri.http` with separate path and query parameters for URIs known at compile time. This improves readability and prevents runtime parsing errors. ```dart // Prefer: Uri.https('jsonplaceholder.typicode.com', '/todos/1') Uri.https('pokeapi.co', '/api/v2/ability/', {'limit': '1'}) ``` ```dart // Over (path / query smuggled into the authority — parsed at runtime anyway): Uri.https('pokeapi.co/api/v2/ability/?limit=1') ``` ```dart // Over (full string parse — same drawback, plus scheme is now stringly-typed): Uri.parse('https://pokeapi.co/api/v2/ability/?limit=1') ``` -------------------------------- ### Strict All Reachable Policy Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Configure the checker to require all probes to succeed for a connection to be considered reachable. Recommended with a curated probe list. ```dart final checker = InternetConnection( policy: const AllReachablePolicy(), ); ``` -------------------------------- ### StreamController.broadcast() Lazy Allocation Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/APPENDIX.md The backing StreamController.broadcast() is instantiated on first access to InternetConnection.events, not at construction. This avoids per-instance broadcast-controller costs for checkers whose consumers only watch onStatusChange. ```dart StreamController.broadcast() ``` -------------------------------- ### ViewModel Member Ordering Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Organize ViewModel members in a specific order: external references, constructors, state fields, init(), getters, logic methods, private helpers, and dispose(). This improves code navigation. ```dart // 1. External-ref fields final AuthService _authService; // 2. Constructors ViewModel(this._authService); // 3. State fields final _isBusyNotifier = ValueNotifier(false); ValueListenable get isBusy => _isBusyNotifier; // 4. init() void init() { // Setup streams, trigger initial loads, etc. } // 5. Getters // ... // 7. Logic methods void onLoginPressed() { _isBusyNotifier.value = true; // ... login logic ... _isBusyNotifier.value = false; } // 8. Private helpers void _runCheck() { // ... internal logic ... } // 9. dispose() void dispose() { _isBusyNotifier.dispose(); // ... dispose other resources ... } ``` -------------------------------- ### Benchmark Directory Layout Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md This snippet shows the directory structure of the benchmark suite. The benchmark directory is excluded from the published pub.dev tarball. ```text benchmark/ ├── README.md this file ├── harness/ shared Dart utilities for both layers ├── micro/ benchmark_harness-based micro-benches ├── scenarios/ long-running stateful scenarios ├── python/ orchestration + analysis + reporting ├── reports/ committed report + compare output (PNGs + .md) ├── results-local/ contributor-local run outputs (gitignored) ├── results/ legacy run-output dir (gitignored; kept for older workflows) └── build/ AOT-compiled scenario exes (gitignored) ``` -------------------------------- ### Long-Running Benchmark Capture with System Wake Lock Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md Command to run a long benchmark (N=30 iterations) while preventing macOS from sleeping and ensuring real-time output flushing. Use `python -u` or `PYTHONUNBUFFERED=1` for real-time output. ```bash # macOS will sleep the system mid-run and kill the python process. # Wrap the command in `caffeinate -dimsu` to keep the system fully awake # (display + idle + system + user-activity assertions). # # Use `python -u` (or set `PYTHONUNBUFFERED=1`) so the per-scenario # progress lines flush to the terminal in real time — otherwise the # output buffers for several minutes at a time and looks frozen. caffeinate -dimsu uv run python -u run.py run \ --iterations 30 --out ../results-local/main-n30/ ``` -------------------------------- ### Use Custom Probe Targets Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Specify a list of custom URIs to probe for internet reachability. This allows tailoring the checks to specific critical endpoints. ```dart final connectivity = BetterInternetConnectivityChecker( targets: [ Uri.parse('https://google.com'), Uri.parse('https://cloudflare.com'), ], ); final status = await connectivity.check(); print('Status with custom targets: $status'); ``` -------------------------------- ### Inject Custom HTTP Client Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Provide a custom http.Client instance for probes, useful for handling proxies, middleware, or for testing with a MockClient. ```dart import 'package:http/http.dart' as http; final checker = InternetConnection( probe: HttpProbe.head(client: myHttpClient), ); ``` -------------------------------- ### Perform Strict Static Analysis Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Run strict-mode static analysis to check for code quality and potential issues. Dart 3.10+ is required. ```bash dart analyze ``` -------------------------------- ### Callback Methods with View-Event Suffix Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Name callback methods from the view's perspective using the pattern 'on', where Suffix matches the widget type. This clarifies the origin of the event. ```dart // Button example void onRunCheckPressed() => _runCheck(); // SwitchListTile example void onAcceptAnyTwoXxToggled({required bool value}) => _shouldAcceptAnyTwoXxNotifier.value = value; // Slider.onChanged example void onSlowThresholdSliderChanged(double value) => _updateThreshold(value); // Slider.onChangeEnd example void onSlowThresholdSliderReleased() => _saveThreshold(); // DropdownButton example void onMethodSelected(String? method) => _setSelectedMethod(method); // TextField.onChanged example void onUrlChanged(String url) => _updateUrl(url); ``` -------------------------------- ### Inject a Custom http.Client Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Provide a custom http.Client instance for making HTTP requests. This is useful for configuring custom headers, proxies, or interceptors. ```dart import 'package:http/http.dart' as http; final customClient = http.Client(); final connectivity = BetterInternetConnectivityChecker( httpClient: customClient, ); // Remember to close the client when done if it's not managed elsewhere // customClient.close(); ``` -------------------------------- ### Check Internet Connectivity Once Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Perform a single check of internet connectivity. This is useful for immediate status verification. ```dart final connectivity = BetterInternetConnectivityChecker(); final status = await connectivity.check(); print('Internet status: $status'); ``` -------------------------------- ### Integrate connectivity_plus with InternetConnection Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Wire the InternetConnection checker with Flutter's connectivity_plus package. The checker accepts any Stream as an external trigger. ```dart import 'package:connectivity_plus/connectivity_plus.dart'; final checker = InternetConnection( externalRecheckTrigger: Connectivity().onConnectivityChanged.map(noopWithVal), ); ``` -------------------------------- ### Detect Slow Connections Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Configure the checker to identify slow internet connections based on a response time threshold. This helps in adapting application behavior for slower networks. ```dart final connectivity = BetterInternetConnectivityChecker( probeTimeout: const Duration(seconds: 5), qualityThreshold: const Duration(seconds: 2), ); final status = await connectivity.check(); if (status case Reachable(quality: Quality.slow)) { print('Detected a slow connection.'); } ``` -------------------------------- ### One-shot Internet Check Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Perform a single check of the internet connection status. Remember to dispose of the checker when done to release resources. ```dart import 'package:better_internet_connectivity_checker/better_internet_connectivity_checker.dart'; Future main() async { final checker = InternetConnection(); final status = await checker.checkOnce(); print(status is Reachable ? 'online' : 'offline'); await checker.dispose(); } ``` -------------------------------- ### Pattern Match Connectivity Status Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Use pattern matching to handle different connectivity states like Reachable, Unreachable, and Slow connection. This allows for specific actions based on the status. ```dart final status = await connectivity.check(); switch (status) { case Reachable(quality: Quality.good): print('Internet is reachable and fast!'); case Reachable(quality: Quality.slow): print('Internet is reachable, but slow.'); case Unreachable(): print('Internet is unreachable.'); } ``` -------------------------------- ### Observable VM State with ValueNotifier Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Exposes observable VM state as ValueListenable, backed by a private ValueNotifier. Views subscribe via ValueListenableBuilder. Avoids notifyListeners() by directly updating the notifier's value. ```dart final _probeMethodNotifier = ValueNotifier(ProbeMethod.head); ValueListenable get probeMethodListenable => _probeMethodNotifier; ``` -------------------------------- ### Async Wait Extensions for Futures Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Use `dart:async` wait extensions for managing multiple futures, preferring record forms for fixed numbers of differently-typed futures and iterable forms for dynamic numbers of same-typed futures. ```dart final (anyStatus, allStatus) = await (any.checkOnce(), all.checkOnce()).wait; ``` ```dart final results = await Future.wait([any.checkOnce(), all.checkOnce()]); final anyStatus = results.first; final allStatus = results[1]; ``` ```dart final results = await targets.map(probe.probe).wait; ``` ```dart final results = await Future.wait(targets.map(probe.probe)); ``` -------------------------------- ### Wire connectivity_plus for Flutter Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Integrate with the `connectivity_plus` package in Flutter to trigger rechecks based on OS-reported network changes. This ensures the checker stays up-to-date with system connectivity events. ```dart import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:better_internet_connectivity_checker/better_internet_connectivity_checker.dart'; // Assuming 'connectivity' is an instance of BetterInternetConnectivityChecker final connectivity = BetterInternetConnectivityChecker(); Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { // Trigger a recheck when the system reports a change connectivity.externalRecheckTrigger.add(result); }); ``` -------------------------------- ### Benchmark Result JSON Schema Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/benchmark/README.md The schema for JSON files generated by each scenario run. It includes scenario details, SDK and package versions, timestamps, collected samples, and summary statistics. ```json { "scenario": "", "iteration": , "sdk_version": "", "package_version": "", "git_sha": "", "started_at": "", "samples": { "": [, ...] }, "summary": { "": } } ``` -------------------------------- ### Listen to Connectivity Status Changes Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Subscribe to a stream of connectivity status changes. This is ideal for real-time updates and reacting to network transitions. ```dart final connectivity = BetterInternetConnectivityChecker(); connectivity.statusStream.listen((status) { print('Connectivity changed: $status'); }); ``` -------------------------------- ### Listen to Internet Status Changes Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Subscribe to status changes to react to network transitions. The stream only emits when the status actually changes, preventing redundant events. ```dart final checker = InternetConnection(); final subscription = checker.onStatusChange.listen((status) { // Same status kind is not re-emitted, so this fires only on real transitions. }); // later: await subscription.cancel(); await checker.dispose(); ``` -------------------------------- ### Naming Boolean Fields with Modal Verbs Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Prefix boolean fields with modal verbs like 'should', 'can', 'may', or 'must' to clearly indicate their purpose. 'should' is preferred for user preferences and UI toggles. ```dart bool acceptAnyTwoXx = false; bool get shouldAcceptAnyTwoXx => _shouldAcceptAnyTwoXxNotifier.value; set shouldAcceptAnyTwoXx(bool value) => _shouldAcceptAnyTwoXxNotifier.value = value; // Callback method example void onAcceptAnyTwoXxToggled({required bool value}) => _shouldAcceptAnyTwoXxNotifier.value = value; ``` -------------------------------- ### Attach PrintingConnectivityObserver for logging Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Use the PrintingConnectivityObserver to log all connectivity events via dart:developer's log(). This integrates with Flutter DevTools and surfaces via stdout in plain Dart. ```dart final checker = InternetConnection(); final subscription = attachObserver( checker.events, const PrintingConnectivityObserver(), ); // ... later, when shutting down: await subscription.cancel(); // explicit cleanup, OR await checker.dispose(); // closes events; the subscription cancels automatically ``` -------------------------------- ### ConnectivityObserver Documentation Warning Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/APPENDIX.md A warning preserved by the refactor indicates that heavy work or blocking IO inside an override will stall the checker's scheduling loop. ```dart ConnectivityObserver ``` -------------------------------- ### Configure Strict Aggregation Policy Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Set the aggregation policy to 'strict', requiring all probes to succeed for the connection to be considered reachable. This is useful for critical applications where all endpoints must be available. ```dart final connectivity = BetterInternetConnectivityChecker( aggregation: Aggregation.strict, ); final status = await connectivity.check(); print('Status with strict aggregation: $status'); ``` -------------------------------- ### Collection Literals with `for` and `if` Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Prefer using collection literals with `for` and `if` for creating lists, especially in widget trees, over `Iterable.map(…).toList()`. This improves readability and allows for type inference. ```dart DropdownButton( value: viewModel.probeMethod, items: [ for (final method in ProbeMethod.values) DropdownMenuItem(value: method, child: Text(method.label)), ], onChanged: …, ) ``` ```dart DropdownButton( value: viewModel.probeMethod, items: ProbeMethod.values .map((m) => DropdownMenuItem(value: m, child: Text(m.label))) .toList(), onChanged: …, ) ``` -------------------------------- ### Configure Slow Connection Threshold Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Define a duration to classify a connection as 'slow'. This threshold is used to set the 'quality' field in the Reachable status. ```dart final checker = InternetConnection( slowThreshold: const Duration(milliseconds: 500), ); ``` -------------------------------- ### Custom Probe Targets Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Specify custom endpoints for reliability checks. You can define custom URIs and success criteria for probes. ```dart final checker = InternetConnection( targets: [ ProbeTarget(uri: Uri.parse('https://my-api.example.com/health')), ProbeTarget( uri: Uri.parse('https://other.example.com/ping'), isSuccess: (response) => response.statusCode == 204, ), ], ); ``` -------------------------------- ### Subscribe to CheckCompletedEvent for custom logging Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Directly subscribe to the InternetConnection.events stream and filter for CheckCompletedEvent to perform custom actions, such as logging the result. ```dart final checker = InternetConnection(); checker.events .whereType() .listen((e) => log('check completed: ${e.result}')); ``` -------------------------------- ### Prefer Column spacing over interleaved Gaps Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Use the `spacing` parameter on `Column` or `Row` for uniform gaps between children. This is preferred over manually inserting `Gap` widgets. ```dart Column( crossAxisAlignment: .start, spacing: 8, children: [Text(...), StatusBadge(...), _ResultDetail(...)], ) // Over: Column( crossAxisAlignment: .start, children: [Text(...), const Gap(8), StatusBadge(...), const Gap(8), _ResultDetail(...)], ) ``` -------------------------------- ### Named Argument for Boolean Parameters Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md When calling methods with a bare boolean parameter, use named arguments to improve clarity, especially to avoid the 'avoid_positional_boolean_parameters' lint. ```dart // VM void onAcceptAnyTwoXxToggled({required bool value}) => _shouldAcceptAnyTwoXxNotifier.value = value; // View onChanged: (value) => viewModel.onAcceptAnyTwoXxToggled(value: value), ``` -------------------------------- ### Android Internet Permission Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Add the INTERNET permission to your AndroidManifest.xml. This is required for network probes to function correctly on release builds. ```xml ``` -------------------------------- ### Shell Scripting Lint Contract with ShellCheck Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Enforce code quality in shell scripts using ShellCheck. Prefer disabling rules with comments for simple cases where the code is correct but flagged by the linter. ```shell # shellcheck disable=SC2154 # Why: ShellCheck cannot follow assignment-then-use within the same quoted trap string. ``` -------------------------------- ### Use List.unmodifiable for Immutable Collections Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Prefer `List.unmodifiable` to create defensive snapshots of collections, preventing external mutation of internal state. Use `UnmodifiableListView` only when live read-through visibility into mutable internal state is specifically required. ```dart // Prefer — defensive snapshot, caller-supplied list cannot mutate our state: class Foo { Foo(List input) : _xs = List.unmodifiable(input); final List _xs; } ``` ```dart // Reserve — read-through view of private mutable internal state: class EventLog { final List _events = []; List get events => UnmodifiableListView(_events); void add(Event e) => _events.add(e); } ``` -------------------------------- ### Pattern Matching Internet Status Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/README.md Use exhaustive switch statements to handle different InternetStatus variants like Reachable and Unreachable. This ensures all possible states are considered. ```dart switch (await checker.checkOnce()) { case Reachable(:final responseTime, :final quality): print('online — $quality, ${responseTime.inMilliseconds} ms'); case Unreachable(:final failedProbes): print('offline — ${failedProbes.length} probes failed'); } ``` -------------------------------- ### Async action button with busy state Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/example/CODESTYLE.md Use `AsyncIconActionButton` to handle asynchronous operations in buttons. It automatically manages the busy state, showing a spinner and busy label, and debounces taps. ```dart AsyncIconActionButton( onPressed: viewModel.onProbePressed, idleIcon: Icons.send, idleLabel: 'Probe URL', busyLabel: 'Probing…', ) ``` -------------------------------- ### Using @docImport for Documentation-Only References in Dart Source: https://github.com/lahaluhem/better_internet_connectivity_checker/blob/main/CODESTYLE.md Use the `@docImport` directive for symbols referenced only in dartdoc comments to avoid polluting the runtime import graph. This directive satisfies comment references without adding a runtime dependency. ```dart /// @docImport '../internet_connection.dart'; library; import '../status/internet_status.dart'; // Real code import — InternetStatus is used. ```