### Dart Named Constructors Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates how to bridge Dart's named constructors by mapping their names to adapter functions. Includes an example of a 'guest' constructor and argument validation. ```dart class User { String name; int age; User(this.name, this.age); User.guest() : name = 'Guest', age = 0; } final userDefinition = BridgedClass( nativeType: User, name: 'User', constructors: { '': (visitor, positionalArgs, namedArgs) { /* ... default constructor ... */ }, 'guest': (visitor, positionalArgs, namedArgs) { if (positionalArgs.isEmpty && namedArgs.isEmpty) { return User.guest(); } throw ArgumentError('User.guest constructor expects no arguments.'); }, }, // ... members ... ); ``` -------------------------------- ### Dart Constructor Argument Validation Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Provides an example of validating arguments for a Dart constructor adapter, specifically for a named constructor 'withId'. It checks the number and types of positional and named arguments. ```dart 'withId': (visitor, positionalArgs, namedArgs) { if (positionalArgs.length != 1 || positionalArgs[0] is! String) { throw ArgumentError('Named constructor \'withId\' expects 1 String positional arg (id)'); } final id = positionalArgs[0] as String; int initialValue = 0; if (namedArgs.containsKey('initialValue')) { if (namedArgs['initialValue'] is! int?) { // Allows int or null throw ArgumentError('Named arg \'initialValue\' must be an int?'); } initialValue = namedArgs['initialValue'] as int? ?? 0; // Handle null } return NativeCounter.withId(id, initialValue: initialValue); } ``` -------------------------------- ### Get d4rt Dependencies Source: https://github.com/kodjodevf/d4rt/blob/main/README.md After adding d4rt to your pubspec.yaml, run this command in your project's root directory to fetch the dependency. ```sh dart pub get ``` -------------------------------- ### Dart Static Getters Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Illustrates how to bridge static getters in Dart. It shows the native definition and how it's accessed from the script. ```dart staticGetters: { 'staticValue': (visitor) => NativeCounter.staticValue, } ``` -------------------------------- ### Dart Instance Method Bridging (increment) Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates bridging a native Dart method 'increment' for a 'NativeCounter' class. It handles optional integer arguments and returns null for void methods. The example shows how to call this bridged method from a script. ```dart // Native: void NativeCounter.increment([int amount = 1]); methods: { 'increment': (visitor, target, positionalArgs, namedArgs) { if (target is NativeCounter) { if (positionalArgs.isEmpty) { target.increment(); } else if (positionalArgs.length == 1 && positionalArgs[0] is int) { target.increment(positionalArgs[0] as int); } else { throw ArgumentError('increment expects 0 or 1 int argument'); } return null; // For void methods } throw TypeError(); }, } // Script: myCounter.increment(); myCounter.increment(5); ``` -------------------------------- ### Dart Operator Bridging (`[]`, `[]=`) Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Explains and provides examples for bridging Dart's index operators (`[]` and `[]=`) as instance methods. It shows how to define these bridges for types like `Uint8List`, including argument validation and return value handling. ```dart // For Uint8List[] '[]': (visitor, target, positionalArgs, namedArgs) { if (target is Uint8List && positionalArgs.length == 1 && positionalArgs[0] is int) { return target[positionalArgs[0] as int]; } throw ArgumentError("Invalid arguments for Uint8List[index]"); } ``` ```dart // For Uint8List[]= '[]=': (visitor, target, positionalArgs, namedArgs) { if (target is Uint8List && positionalArgs.length == 2 && positionalArgs[0] is int && positionalArgs[1] is int) { final index = positionalArgs[0] as int; final value = positionalArgs[1] as int; target[index] = value; return value; // Dart's []= operator returns the assigned value. } throw ArgumentError("Invalid arguments for Uint8List[index] = value."); } ``` -------------------------------- ### Bridging Dart Stream with nativeNames Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md This example demonstrates how to use `nativeNames` to bridge the Dart `Stream` class, including its internal implementations like `_MultiStream` and `_ControllerStream`. It shows how to define the `BridgedClass` with `nativeNames` and map methods like `toList` to ensure compatibility with various stream types. ```dart static BridgedClass get definition => BridgedClass( nativeType: Stream, name: 'Stream', nativeNames: ['_MultiStream', '_ControllerStream', /* ... */], // Now Stream.fromIterable([1,2,3]).toList() works in scripts! ); ``` ```dart static BridgedClass get definition => BridgedClass( nativeType: Stream, name: 'Stream', // Internal Stream implementations discovered through testing: // _MultiStream: Stream.fromIterable() // _ControllerStream: StreamController().stream // _BroadcastStream: broadcast streams nativeNames: [ '_MultiStream', // fromIterable, fromFuture '_ControllerStream', // StreamController '_BroadcastStream', // broadcast streams // ... add more as discovered ], methods: { 'toList': (visitor, target) => (target as Stream).toList(), // This now works for ALL the mapped internal types! }, ); ``` -------------------------------- ### Return Bridged Instances from Native Methods in Dart Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Explains how d4rt automatically wraps native objects returned from bridged methods (sync or async) into `BridgedInstance` objects usable in the script. ```dart // Native: NativeCounter AsyncProcessor.createCounterSync(int val, String id); // Adapter: 'createCounterSync': (visitor, target, positionalArgs, namedArgs) { if (target is AsyncProcessor && positionalArgs.length == 2 && positionalArgs[0] is int && positionalArgs[1] is String) { return target.createCounterSync(positionalArgs[0] as int, positionalArgs[1] as String); // Returns NativeCounter, d4rt wraps it. } throw ArgumentError('Invalid args'); } // Script: // var processor = AsyncProcessor(); // var counter = processor.createCounterSync(100, 'sync-id'); // counter is a usable bridged Counter // counter.increment(); // print(counter.value); // 101 ``` -------------------------------- ### Execute Dart Code Dynamically with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/README.md This example demonstrates how to use the d4rt interpreter to execute a Dart code string dynamically. It includes a simple Fibonacci function and prints the result. ```dart import 'package:d4rt/d4rt.dart'; void main() { final code = ''' int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } main() { return fib(6); } '''; final interpreter = D4rt(); final result = interpreter.execute(source: code); print('Result: $result'); // Result: 8 } ``` -------------------------------- ### Dart Static Methods Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Shows how to bridge static methods in Dart, including argument validation for positional and named arguments. ```dart staticMethods: { 'staticMethod': (visitor, positionalArgs, namedArgs) { if (positionalArgs.length == 1 && positionalArgs[0] is String) { return NativeCounter.staticMethod(positionalArgs[0] as String); } throw ArgumentError('staticMethod expects 1 string argument'); }, } ``` -------------------------------- ### Install d4rt Dependency Source: https://github.com/kodjodevf/d4rt/blob/main/README.md This snippet shows how to add the d4rt library as a dependency in your Flutter or Dart project's pubspec.yaml file. ```yaml dependencies: d4rt: # latest version ``` -------------------------------- ### Dart Instance Setters Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates bridging instance setters in Dart, including type checking for both the target object and the value being set. ```dart setters: { 'value': (visitor, target, value) { if (target is NativeCounter && value is int) { target.value = value; } else { throw ArgumentError('Setter expects NativeCounter target and int value'); } }, } ``` -------------------------------- ### Dart Instance Getters Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Explains how to bridge instance getters in Dart, accessing members on a specific object instance. ```dart getters: { 'value': (visitor, target) { if (target is NativeCounter) return target.value; throw TypeError(); // Or a more specific error }, } ``` -------------------------------- ### Pass Bridged Instances as Arguments in Dart Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates how to pass instances of bridged classes as arguments to native methods. The adapter needs to handle potential `BridgedInstance` wrappers or unwrapped native objects. ```dart // Native: bool NativeCounter.isSame(NativeCounter other); // Bridge Adapter for 'isSame': 'isSame': (visitor, target, positionalArgs, namedArgs) { if (target is NativeCounter && positionalArgs.length == 1) { final arg = positionalArgs[0]; NativeCounter? otherNative; if (arg is BridgedInstance && arg.nativeObject is NativeCounter) { otherNative = arg.nativeObject as NativeCounter; } else if (arg is NativeCounter) { // If already unwrapped otherNative = arg; } if (otherNative != null) { return target.isSame(otherNative); } throw ArgumentError('Invalid argument for isSame: Expected Counter, got ${arg?.runtimeType}'); } throw ArgumentError('Invalid arguments for isSame'); } // Script: // var c1 = Counter(10); // var c2 = Counter(10); // print(c1.isSame(c2)); // true ``` -------------------------------- ### Dart Static Setters Bridging Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates bridging static setters in Dart, including type validation for the value being set. ```dart staticSetters: { 'staticValue': (visitor, value) { if (value is! int) throw ArgumentError('staticValue requires an int'); NativeCounter.staticValue = value; }, } ``` -------------------------------- ### Invoke Methods and Getters with interpreter.invoke() Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Shows how to use `interpreter.invoke()` to call methods or access getters on the last evaluated instance from `interpreter.execute()`. This is useful for testing or interacting with instances without writing a full script, and it correctly handles overridden methods. ```Dart // Setup final source = ''' class MyWidget { String _label = "Initial"; String get label => _label; void updateLabel(String newLabel) { _label = newLabel; } String format(String prefix) => prefix + ": " + _label; } main() => MyWidget(); // Script returns an instance '''; final instance = interpreter.execute(source: source) as InterpretedInstance; // Invoke getter 'label' var label = interpreter.invoke('label', []); print(label); // "Initial" // Invoke method 'updateLabel' interpreter.invoke('updateLabel', ['New Value']); // Invoke getter again to see change label = interpreter.invoke('label', []); print(label); // "New Value" // Invoke method with arguments var formatted = interpreter.invoke('format', ['INFO']); print(formatted); // "INFO: New Value" ``` -------------------------------- ### Dart Asynchronous Method Bridging (Future) Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Illustrates how d4rt bridges native Dart methods that return a `Future`. It shows how to define bridges for methods returning `Future`, `Future`, and `Future`, allowing `await` usage in scripts. Error propagation via `try-catch` is also demonstrated. ```dart // Native Class class AsyncService { Future fetchData(String id) async { await Future.delayed(Duration(milliseconds: 100)); return "Data for $id"; } Future performAction() async { /* ... */ } Future createCounterAsync(int val) async { /* ... */ return NativeCounter(val); } } // Bridge Definition (partial) final asyncServiceDefinition = BridgedClass( nativeType: AsyncService, name: 'AsyncService', constructors: { /* ... */ }, methods: { 'fetchData': (visitor, target, positionalArgs, namedArgs) { if (target is AsyncService && positionalArgs.length == 1 && positionalArgs[0] is String) { return target.fetchData(positionalArgs[0] as String); // Return Future } throw ArgumentError('Invalid args for fetchData'); }, 'performAction': (visitor, target, positionalArgs, namedArgs) { if (target is AsyncService && positionalArgs.isEmpty) { return target.performAction(); // Return Future } throw ArgumentError('Invalid args for performAction'); }, 'createCounterAsync': (visitor, target, positionalArgs, namedArgs) { if (target is AsyncService && positionalArgs.length == 1 && positionalArgs[0] is int) { return target.createCounterAsync(positionalArgs[0] as int); // Return Future } throw ArgumentError('Invalid args for createCounterAsync'); } } ); // d4rt script import 'package:myapp/services.dart'; // Assuming AsyncService is registered here main() async { var service = AsyncService(); // Assuming a bridged constructor var data = await service.fetchData('user123'); print(data); // "Data for user123" await service.performAction(); print('Action performed'); var counter = await service.createCounterAsync(50); // counter will be a bridged Counter instance counter.increment(); print(counter.value); // 51 try { // await service.methodThatFails(); // If it returns a Future.error } catch (e) { print('Caught error: $e'); } return data; } ``` -------------------------------- ### Bridge Default Constructor for Dart Class Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Shows how to bridge the default (unnamed) constructor of a native Dart class. The adapter is registered under an empty string key in the `constructors` map of `BridgedClass`. ```Dart // Native Class class NativeLogger { String prefix; NativeLogger(this.prefix); void log(String message) => print('$prefix: $message'); } // Bridge Definition final loggerDefinition = BridgedClass( nativeType: NativeLogger, name: 'Logger', constructors: { '': (visitor, positionalArgs, namedArgs) { if (positionalArgs.length == 1 && positionalArgs[0] is String) { return NativeLogger(positionalArgs[0] as String); } throw ArgumentError('Logger constructor expects one string argument (prefix).'); }, }, // ... methods ... ); // Script Usage: // var logger = Logger('MyScript'); // Calls the bridged default constructor ``` -------------------------------- ### Access Native Object with bridgedSuperObject Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates how to access the underlying native object of an `InterpretedInstance` that extends a bridged class using the `bridgedSuperObject` property. This allows direct interaction with the native methods, bypassing any overrides. ```Dart // (From test/bridge/bridged_class_test.dart) // NativeCounter nativeCounter = interpretedInstance.bridgedSuperObject as NativeCounter; // nativeCounter.increment(2); // Calls the *actual* native method, bypassing overrides ``` -------------------------------- ### Handle Native Errors in Dart with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Describes how exceptions thrown in native code (like `StateError`) are caught by d4rt and re-thrown as `RuntimeError` in the script, preserving the original error message. ```dart // Native: // void NativeCounter.dispose() { _isDisposed = true; } // int get value { if (_isDisposed) throw StateError('Instance disposed'); return _value; } // Script: // var c = Counter(1); // c.dispose(); // try { // print(c.value); // } catch (e) { // print('Error: $e'); // Error: RuntimeError: Unexpected error: Bad state: Instance disposed // } ``` -------------------------------- ### Register Dart Class with Bridged Members Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Illustrates how to bridge a native Dart class using `BridgedClass`. This includes defining the `nativeType`, `name`, and mapping constructors and instance members (getters, setters, methods) for use in d4rt scripts. ```Dart // Bridge setup code // Assume NativeCounter class is defined final counterDefinition = BridgedClass( nativeType: NativeCounter, name: 'Counter', // ... constructor and member definitions ... ); interpreter.registerBridgedClass(counterDefinition, 'package:myapp/native_utils.dart'); // d4rt script import 'package:myapp/native_utils.dart'; main() { var myCounter = Counter(10); // Using a bridged constructor myCounter.increment(); return myCounter.value; } ``` -------------------------------- ### Extend Bridged Classes in Dart Scripts with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Shows how to create Dart classes that extend native bridged classes. This includes calling superclass constructors and overriding methods or accessing properties using `super`. ```dart // d4rt script import 'package:myapp/native_utils.dart'; // Where 'Counter' is bridged class ScriptCounter extends Counter { String scriptId; // Call super constructor (default or named) ScriptCounter(int initialValue, String nativeId, this.scriptId) : super(initialValue, nativeId); // Calls Counter(value, id) ScriptCounter.special(String nativeId, this.scriptId, {int val = 0}) : super.withId(nativeId, initialValue: val); // Calls Counter.withId(...) // Override a bridged method @override void increment([int amount = 1]) { super.value = super.value + (amount * 2); // Custom logic, using super.value print('ScriptCounter incremented!'); } String getInfo() { return "ScriptCounter($scriptId) with native id $id and value $value"; // Accesses 'id' and 'value' from bridged 'Counter' superclass } } main() { var sc = ScriptCounter(10, 'native-A', 'script-X'); sc.increment(3); // Calls overridden increment. 10 + (3*2) = 16 print(sc.value); // 16 print(sc.getInfo()); // "ScriptCounter(script-X) with native id native-A and value 16" var sc2 = ScriptCounter.special('native-B', 'script-Y', val: 5); print(sc2.value); // 5 return sc.value; } ``` -------------------------------- ### Bridge Dart Enum with Getters and Methods Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates how to define a `BridgedEnumDefinition` for a Dart enum that includes fields, getters, and methods. It shows how to map these members to be accessible from d4rt scripts, including overriding the `toString` behavior. ```Dart // Native Dart code enum ComplexEnum { itemA('Data A', 10), itemB('Data B', 20); final String data; final int number; const ComplexEnum(this.data, this.number); String get info => '$data-$number (native)'; int multiply(int factor) => number * factor; bool isItemA() => this == ComplexEnum.itemA; @override String toString() => "NativeComplexEnum.$name"; // Native toString } // Bridge setup code final complexEnumDefinition = BridgedEnumDefinition( name: 'MyComplexEnum', values: ComplexEnum.values, getters: { 'data': (visitor, target) => (target as ComplexEnum).data, 'number': (visitor, target) => (target as ComplexEnum).number, 'info': (visitor, target) => (target as ComplexEnum).info, // Bridge the native getter }, methods: { 'multiply': (visitor, target, positionalArgs, namedArgs) { if (target is ComplexEnum && positionalArgs.length == 1 && positionalArgs[0] is int) { return target.multiply(positionalArgs[0] as int); } throw ArgumentError('Invalid arguments for multiply'); }, 'isItemA': (visitor, target, positionalArgs, namedArgs) { if (target is ComplexEnum && positionalArgs.isEmpty && namedArgs.isEmpty) { return target.isItemA(); } throw ArgumentError('Invalid arguments for isItemA'); }, // Optionally, override toString behavior for the bridged enum value 'toString': (visitor, target, positionalArgs, namedArgs) { if (target is ComplexEnum) { return 'MyComplexEnum.${target.name} (bridged)'; } throw ArgumentError('Invalid target for toString'); }, }, ); interpreter.registerBridgedEnum(complexEnumDefinition, 'package:myapp/complex_types.dart'); // d4rt script import 'package:myapp/complex_types.dart'; main() { var item = MyComplexEnum.itemA; print(item.data); // "Data A" print(item.number); // 10 print(item.info); // "Data A-10 (native)" print(item.multiply(3)); // 30 print(item.isItemA()); // true print(item); // "MyComplexEnum.itemA (bridged)" return item.info; } ``` -------------------------------- ### Bridge Dart Class with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/README.md This example shows how to bridge a custom Dart class ('MyClass') with d4rt, allowing it to be instantiated and used within interpreted Dart code. It defines constructors, methods, and getters for the bridged class. ```dart import 'package:d4rt/d4rt.dart'; class MyClass { int value; MyClass(this.value); int doubleValue() => value * 2; } final myClassBridge = BridgedClass( nativeType: MyClass, name: 'MyClass', constructors: { '': (InterpreterVisitor visitor, List positionalArgs, Map namedArgs) { if (positionalArgs.length == 1 && positionalArgs[0] is int) { return MyClass(positionalArgs[0] as int); } throw ArgumentError('MyClass constructor expects one integer argument.'); }, }, methods: { 'doubleValue': (InterpreterVisitor visitor, Object target, List positionalArgs, Map namedArgs) { if (target is MyClass) { return target.doubleValue(); } throw TypeError(); }, }, getters: { 'value': (InterpreterVisitor? visitor, Object target) { if (target is MyClass) { return target.value; } throw TypeError(); }, }, ); void main() { final interpreter = D4rt(); interpreter.registerBridgedClass(myClassBridge, 'package:example/my_class_library.dart'); final code = ''' import 'package:example/my_class_library.dart'; main() { var obj = MyClass(21); return obj.doubleValue(); } '''; final result = interpreter.execute(source: code); print(result); // 42 } ``` -------------------------------- ### Bridge Dart Enum with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Demonstrates how to bridge a native Dart enum to be used within the d4rt interpreter. This involves defining a `BridgedEnumDefinition` with the enum's name and values, and then registering it with the interpreter. The bridged enum can then be imported and used in d4rt scripts. ```dart // Native Dart code enum NativeColor { red, green, blue } // Bridge setup code import 'package:d4rt/d4rt.dart'; // Assume NativeColor is defined in the same scope or imported // 1. Define the bridge final colorDefinition = BridgedEnumDefinition( name: 'BridgedColor', // How the enum will be known in the script values: NativeColor.values, // Provide the native enum's values ); // 2. Register with the interpreter // The library URI is used for import statements in the script. interpreter.registerBridgedEnum(colorDefinition, 'package:myapp/custom_types.dart'); ``` ```dart // d4rt script import 'package:myapp/custom_types.dart'; // Import the library where BridgedColor was registered main() { var myColor = BridgedColor.green; print(myColor.name); // Accesses the 'name' property (e.g., "green") print(myColor.index); // Accesses the 'index' property (e.g., 1) print(myColor); // Calls toString(), e.g., "BridgedColor.green" if (myColor == BridgedColor.green) { print('It is green!'); } return myColor.name; } ``` -------------------------------- ### Map Native Class Names with nativeNames Source: https://github.com/kodjodevf/d4rt/blob/main/BRIDGING_GUIDE.md Illustrates how to use the `nativeNames` parameter within `BridgedClass` to map multiple internal or alternative native class names to a single bridge definition. This resolves `RuntimeError` when the interpreter cannot find a direct bridge for internal Dart types like `_MultiStream`. ```Dart // Example from Stream bridging class StreamAsync { static BridgedClass get definition => BridgedClass( nativeType: Stream, name: 'Stream', // Map all these internal Stream implementations to the same Stream bridge nativeNames: [ '_MultiStream', '_ControllerStream', '_BroadcastStream', '_AsBroadcastStream', '_StreamHandlerTransformer', '_BoundSinkStream', '_ForwardingStream', '_MapStream', '_WhereStream', '_ExpandStream', '_TakeStream', '_SkipStream', '_DistinctStream', ], methods: { // ... your stream methods }, ); } ``` -------------------------------- ### Bridge Dart Enum with d4rt Source: https://github.com/kodjodevf/d4rt/blob/main/README.md This example demonstrates how to bridge a Dart enum ('Color') with d4rt, making it accessible within interpreted code. It shows how to define the enum bridge and use it to access enum values and properties like 'name' and 'index'. ```dart import 'package:d4rt/d4rt.dart'; enum Color { red, green, blue } final colorEnumBridge = BridgedEnumDefinition( name: 'Color', values: Color.values, ); void main() { final interpreter = D4rt(); interpreter.registerBridgedEnum(colorEnumBridge, 'package:example/my_enum_library.dart'); final code = ''' import 'package:example/my_enum_library.dart'; main() { var favoriteColor = Color.green; print('My favorite color is ${favoriteColor.name}'); return favoriteColor.index; } '''; final result = interpreter.execute(source: code); print(result); // 1 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.