Reflectable is a Dart library that allows programmers to eliminate certain usages of dynamic reflection by specialization of reflective code to an equivalent implementation using only static techniques

Overview

This repository provides the Dart package reflectable along with a set of test cases, test_reflectable.

reflectable

Support for generating code that implements a large subset of the features offered by 'dart:mirrors' without relying on 'dart:mirrors' itself. Provides a system based on capabilities to control the amount of reflection support.

test_reflectable

Used to test package reflectable. Also serves as a set of examples of how reflectable can be used.

Comments
  • Confusing UnimplementedError

    Confusing UnimplementedError

    I'm sorry to bother you with all my problems, but I can't seem to solve this one so I'm not sure if it's a bug. I'm trying to port the websockets package to use reflectable, my current WIP is here.

    I got this strange error and I can't seem to find out exactly what it originates from:

    00:33 +0 -1: test/html_test.dart: connecting and closing                                           
      UnimplementedError
      dart:_internal                                                 JsLibraryMirror.libraryDependencies
      package:reflectable/src/reflectable_mirror_based.dart 2237:14  ReflectableImpl._directlySupportedClasses
      package:reflectable/src/reflectable_mirror_based.dart 2323:36  ReflectableImpl._supportedClasses.<fn>
      dart:_internal                                                 JsLinkedHashMap.2.H.computeSignature.V.func
      package:websockets/src/websocket_base.dart 12:1                J.x
      package:reflectable/src/reflectable_mirror_based.dart 2322:12  ReflectableImpl._supportedClasses
      package:reflectable/src/reflectable_mirror_based.dart 635:15   _LibraryMirrorImpl._rawDeclarations.<fn>
      ===== asynchronous gap ===========================
      dart:_internal                                                 _asyncHelper
      package:websockets/src/websocket.dart 23:1                     <fn>
      ===== asynchronous gap ===========================
      dart:_internal                                                 _wrapJsFunctionForAsync
      package:websockets/src/websocket.dart 23:1                     null.<fn>
      ===== asynchronous gap ===========================
      dart:_internal                                                 _wrapJsFunctionForAsync
      test/html_test.dart 27:1                                       main.<fn>
      package:stack_trace                                            StackZoneSpecification._run
    

    It appears as if library dependencies are requested at one point, which my code does not do. The pointers to my code (websocket_base.dart and websocket.dart) are just the declarations of classes, no interactions with reflectable.

    opened by stevenroose 43
  • Example of a simple JSON system using reflectable

    Example of a simple JSON system using reflectable

    Users have been asking for an easy way to do simple JSON decoding for years. Hopefully reflectable can deliver this.

    Here is the use case:

    class Person {
      int age;
      String name;
      List<Address> addresses;
    }
    
    class Address {
      String street;
      String zip;
    }
    
    // Assumptions: no key is used for each top-level object (map), the developer knows what the top-level
    // maps are. The structure of the maps is expected to match the structure of the class.
    final data = '''
    [
      {"age":21, "name":"Bob", "addresses":[{"street":"123 main", "zip":"88443"}, {"street":"555 second", "zip":"99999"}]},
      {"age":3, "name":"Alice", "addresses":[{"street":"222 cedar", "zip":"23456"}]}
    ]
    ''';
    

    We should really make it simple to get a List<Person> from the data string, without code bloat when compiled to JavaScript, and without a source-gen step.

    opened by sethladd 43
  • build_runner takes over 2 min to create a reflectable file

    build_runner takes over 2 min to create a reflectable file

    Recently I needed to update the reflectable file because a property in one of my classes changed.

    I had to update the pubspec.yaml because I was using build_runner 1.0.0 and it is not supported anymore.

    So I'm using reflectable 2.1.0 and latest version of build_runner.

    I remember that, some months ago, the same file was built in a couple of seconds. Now it last more than two minutes for the same file.

    I have discovered that, the more capabilities you add to the class, the delay is greater.

    class Reflector extends Reflectable {
      const Reflector()
          : super(
              newInstanceCapability,
              invokingCapability,
              reflectedTypeCapability,
              typingCapability,
              declarationsCapability,
            );
    }
    
    [INFO] 2m 29s elapsed, 0/1 actions completed.
    [INFO] 2m 30s elapsed, 0/1 actions completed.
    [WARNING] No actions completed for 15.1s, waiting on:
      - reflectable:reflectable on lib/parser/ReflectableClasses.dart
    
    [INFO] 2m 31s elapsed, 0/1 actions completed.
    [INFO] 2m 32s elapsed, 0/1 actions completed.
    [INFO] 2m 33s elapsed, 0/1 actions completed.
    [INFO] 2m 34s elapsed, 0/1 actions completed.
    [INFO] 2m 35s elapsed, 0/1 actions completed.
    [INFO] Running build completed, took 2m 36s
    
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 32ms
    
    [INFO] Succeeded after 2m 36s with 1 outputs (1 actions)
    

    build.yaml

    targets:
      $default:
        builders:
          reflectable:
            generate_for:
              - lib/parser/ReflectableClasses.dart
            options:
              formatted: false
    

    flutter doctor -v

    [✓] Flutter (Channel master, v1.10.7-pre.127, on Mac OS X 10.14.6 18G95, locale en-AR)
        • Flutter version 1.10.7-pre.127 at /Users/ernestofreiberg/flutter
        • Framework revision 75c07ef1a6 (3 hours ago), 2019-10-02 15:36:07 -0700
        • Engine revision aa8fcbb652
        • Dart version 2.6.0 (build 2.6.0-dev.0.0 98b286de21)
    
     
    [✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
        • Android SDK at /Users/ernestofreiberg/Library/Android/sdk
        • Android NDK location not configured (optional; useful for native profiling support)
        • Platform android-28, build-tools 28.0.3
        • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 11.0)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 11.0, Build version 11A420a
        • CocoaPods version 1.7.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 3.4)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin version 37.1.1
        • Dart plugin version 183.6270
        • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    
    [✓] VS Code (version 1.38.1)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.5.1
    
    [✓] Connected device (4 available)
        • Android SDK built for x86 64 • emulator-5554   • android-x64    • Android 9 (API 28) (emulator)
        • macOS                        • macOS           • darwin-x64     • Mac OS X 10.14.6 18G95
        • Chrome                       • chrome          • web-javascript • Google Chrome 77.0.3865.90
        • Headless Server              • headless-server • web-javascript • Flutter Tools
    
    • No issues found!
    
    opened by efreibe 26
  • Reflectable builder fails when using types from dart:ui

    Reflectable builder fails when using types from dart:ui

    When using dart:ui types as constructor parameter types of classes that are reflected on, the builder fails with message:

    NoSuchMethodError: The getter 'library' was called on null.
    Receiver: null
    Tried calling: library
    

    I published a flutter repo with test files that demonstrate the behavior. The tests are here. There are 3 tests:

    1. dart_ui_color_test.dart uses the Color type from dart:ui. The builder fails on this file.
    2. dart_ui_text_align.dart uses the TextAlign type from dart:ui. The builder also fails on this file.
    3. flutter_services_test.dart uses the TextCapitalization type from package:flutter/services.dart. The builder successfully generates code for this file.

    I am using this command to run the reflectable builder:

    flutter packages pub run build_runner build test
    

    From looking at the dart:ui source code I can see that the types that fail are inside of part-of files. When I import the part-of files directly in the test files, the builder works. However, importing part-of files is a compile-time error, which the builder seems to ignore.

    It may also be that the issue is related to dart:ui since it is part of the sdk.

    I'd expect that importing dart:ui should be sufficient to successfully generate reflectable code using the types dart:ui exposes.

    bug 
    opened by fertrig 26
  • Request to refactor to add option to not overwrite the entry-point file

    Request to refactor to add option to not overwrite the entry-point file

    Hi,

    We'd like to try to use reflectable with Flutter, but don't want to pull in barback or transformers. Would it be possible to refactor reflectable to not require/mandate a dep on barback?

    (We'd then take responsibility for wiring reflectable into our build system.)

    Flutter doesn't have any reflection capabilities, so we'd love to experiment with reflectable.

    Thanks very much!

    enhancement 
    opened by sethladd 25
  • Add support for generic attributes

    Add support for generic attributes

    Let say I have next class:

    class Person {
      String id;
    
      List<Address> addresses;
    }
    

    then I need to get, by mean of reflection, the type of the list addresses which is Address at client/browser side

    opened by luisvt 20
  • How to reflect all subclasses of one common abstract base class?

    How to reflect all subclasses of one common abstract base class?

    Hi,

    I am completely new to this framework and I have some questions.

    I have

    1. An abstract base class with a few getters:
    abstract class MyBaseClass {
        String get name;
        List<MyValueType> get values;
    }
    
    1. Several classes that implement MyBaseClass:
    class A implements MyBaseClass {
       @override
       String name = 'AClass';
       
       @override
       List<MyValueType> = [MyValueType.X, MyValueType.Y]; 
    }
    
    class B implements MyBaseClass {
       @override
       String name = 'BClass';
       
       @override
       List<MyValueType> = []; 
    }
    

    My goal is to fetch all classes that implement MyBaseClass and read their properties.

    So, I created:

    class Reflector extends Reflectable {
      const Reflector()
          : super(invokingCapability); 
    }
    
    const reflector = const Reflector();
    
    1. How do I fetch a list of classes? I only found the InstanceMirror.reflect() which only delivers one result, not many.
    2. It is not clear, how the annotation must be set. When trying to fetch all MyBaseClass implementations, do I need to annotate only my abstract MyBaseClass or do I need to annotate classes A and B or do I need to annotate all three classes?
    3. Which capabilities do I need? In my test case I got this exception: NoSuchCapabilityError: no capability to invoke the getter "name" but was not able to solve this.

    Thanks in advance, any help is appreciated!

    opened by S-Man42 18
  • Annotated model in Polymer app causing reflectable transformer to fail

    Annotated model in Polymer app causing reflectable transformer to fail

    This is a bit of a bizarre issue so let me give some context.

    I have a codegen library that uses annotations on models to create serialization code. These models are then used within custom elements. I found that when running with reflectable 0.5.1 that it was having issues with a particular model of mine.

    class Build {
      /// When the build request was received.
      @Serialize.field('created_at')
      DateTime createdAt;
    
      /// The login for the author of the commit.
      @Serialize.field('author')
      String author;
      ...
    }
    

    To use it within a Polymer view I end up creating a proxy object.

    class BuildProxy extends JsProxy implements Build {
      @reflectable
      @override
      DateTime get createdAt => _model.createdAt;
      set createdAt(DateTime value) {
        _model.createdAt = value;
      }
    
      @reflectable
      @override
      String get author => _model.author;
      set author(String value) {
        _model.author = value;
      }
    
      ...
    }
    

    In the generated code there's this bit.

            new r.VariableMirrorImpl(
                r"createdAt",
                32773,
                52,
                const prefix0.JsProxyReflectable(),
                50,
                -1,
                -1,
                const <Object>[const prefix36.field('created_at')]),
    

    The prefix36.field can't be found so running fails.

    The weird thing is there are other values within that object that are reflectable and used in the view. The author field which is also being used within the view is not having this problem. Searching the generated code I don't see any other references to field.

    If I comment out the @Serialize.field for the createdAt things go back to working.

    The only thing I can think of is maybe its zeroing on createdAt because there's a created constructor in Polymer.

    bug 
    opened by donny-dont 18
  • [reflectable 2.2.8] doesn't create main.reflectable

    [reflectable 2.2.8] doesn't create main.reflectable

    After upgrading my flutter, reflectable doesn't create main.reflectable.dart. I don't know what causes this problem but I share my logs.

    flutter packages pub run build_runner build:
    [INFO] Generating build script...
    [INFO] Generating build script completed, took 484ms
    
    [INFO] Initializing inputs
    [INFO] Reading cached asset graph...
    [INFO] Reading cached asset graph completed, took 99ms
    
    [INFO] Checking for updates since last build...
    [INFO] Checking for updates since last build completed, took 1.2s
    
    [INFO] Running build...
    [WARNING] reflectable:reflectable on test/widget_test.dart:
    Your current `analyzer` version may not fully support your current SDK version.
    
    Please try upgrading to the latest `analyzer` by running `flutter packages upgrade`.
    
    Analyzer language version: 2.11.0
    SDK language version: 2.12.0
    
    If you are getting this message and have the latest analyzer please file
    an issue at https://github.com/dart-lang/sdk/issues/new with the title
    "No published analyzer available for language version 2.12.0".
    Please search the issue tracker first and thumbs up and/or subscribe to
    existing issues if present to avoid duplicates.
    
    [INFO] 1.4s elapsed, 0/1 actions completed.
    [INFO] 2.6s elapsed, 0/1 actions completed.
    [INFO] 3.7s elapsed, 0/1 actions completed.
    [INFO] 4.8s elapsed, 0/1 actions completed.
    [INFO] 10.4s elapsed, 0/1 actions completed.
    [INFO] 21.2s elapsed, 0/1 actions completed.
    [WARNING] No actions completed for 21.2s, waiting on:
      - reflectable:reflectable on test/widget_test.dart
    
    [INFO] 22.3s elapsed, 0/1 actions completed.
    [INFO] 23.3s elapsed, 0/1 actions completed.
    [INFO] 24.3s elapsed, 0/1 actions completed.
    [INFO] 25.4s elapsed, 0/1 actions completed.
    [INFO] 26.4s elapsed, 0/1 actions completed.
    [INFO] 27.5s elapsed, 0/1 actions completed.
    [INFO] 28.5s elapsed, 0/1 actions completed.
    [INFO] 29.6s elapsed, 0/1 actions completed.
    [INFO] Running build completed, took 30.4s
    
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 55ms
    
    [INFO] Succeeded after 30.5s with 1 outputs (1 actions)
    
    flutter doctor:
    [✓] Flutter (Channel master, 1.24.0-8.0.pre.117, on Linux, locale en_US.UTF-8)
        • Flutter version 1.24.0-8.0.pre.117 at /home/aliyazdi75/snap/flutter/common/flutter
        • Framework revision 8cb2665118 (32 hours ago), 2020-11-06 16:02:19 +0800
        • Engine revision 0693ee04d1
        • Dart version 2.12.0 (build 2.12.0-21.0.dev)
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
        • Android SDK at /home/aliyazdi75/Android/Sdk
        • Platform android-30, build-tools 29.0.3
        • Java binary at: /home/aliyazdi75/Application/android-studio/jre/bin/java
        • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
        • All Android licenses accepted.
    
    [✓] Chrome - develop for the web
        • Chrome at google-chrome
    
    [✓] Linux toolchain - develop for Linux desktop
        • clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
        • cmake version 3.10.2
        • ninja version 1.8.2
        • pkg-config version 0.29.1
    
    [✓] Android Studio
        • Android Studio at /home/aliyazdi75/Application/android-studio
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • android-studio-dir = /home/aliyazdi75/Application/android-studio
        • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    
    [✓] Connected device (4 available)
        • sdk gphone x86 (mobile) • emulator-5554 • android-x86    • Android 11 (API 30) (emulator)
        • Linux (desktop)         • linux         • linux-x64      • Linux
        • Web Server (web)        • web-server    • web-javascript • Flutter Tools
        • Chrome (web)            • chrome        • web-javascript • Google Chrome 86.0.4240.183
    
    • No issues found!
    
    

    Mention that widget_test.reflectable.dart has been successfully created,

    opened by aliyazdi75 15
  • Help with setting up reflection in Flutter

    Help with setting up reflection in Flutter

    Hello,

    I was able to set up the basic example with the code running inside main().

    But now I want to create new class to play with reflection there a little bit more, and I get this error

    E/flutter ( 6705): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
    E/flutter ( 6705): 'package:reflectable/src/reflectable_transformer_based.dart': Failed assertion: line 197 pos 14: '_dataCache != null': is not true.
    

    Here is my code

    class Reflector extends Reflectable {
      const Reflector()
          : super(invokingCapability); // Request the capability to invoke methods.
    }
    
    const reflector = const Reflector();
    
    void main() {
    
      initializeReflectable();
    
      var reflectTest = new ReflectTest()
      ..invokingCapabilityTest();
    
      runApp(new MyApp());
    
    
    }
    

    and reflect_test.dart

    import 'package:reflectable/mirrors.dart';
    import 'package:reflection_test/main.dart';
    
    class ReflectTest {
    
      void invokingCapabilityTest(){
        A x = new A(10);
        // Reflect upon [x] using the const instance of the reflector:
        InstanceMirror instanceMirror = reflector.reflect(x);
        int weekday = new DateTime.now().weekday;
        // On Fridays we test if 3 is greater than 10, on other days if it is less
        // than or equal.
        String methodName = weekday == DateTime.FRIDAY ? "greater" : "lessEqual";
        // Reflectable invocation:
        print(instanceMirror.invoke(methodName, [3]));
    
      }
    }
    
    @reflector // This annotation enables reflection on A.
    class A {
      final int a;
      A(this.a);
      greater(int x) => x > a;
      lessEqual(int x) => x <= a;
    }
    

    Now, why do I get error? If I try to add reflection_test.dart to build script I get

    [INFO] TransformerBuilder[Reflectable] on reflection_test|lib/reflect_test.dart: Entry point: reflection_test|lib/reflect_test.dart has no member called `main`.
    
    opened by matejthetree 15
  • Build error...

    Build error...

    I added reflection support to xxgreg's mustache lib: https://github.com/MikeMitterer/mustache (works fine) and threw out all mirror-references from my MDL/Dart lib: https://goo.gl/XSPuiN (reflections branch)

    If I try to compile this sample https://goo.gl/nENSsI to JS I get the error below.

    I use 0.4.x because one of the DI dependencies is still using this version... My main problem is that I don't know which feature you mean - maybe I could avoid it but I have no idea what causes this error. (BTW: everything works fine in VM)

    Error:

    Build error:
    Transform Reflectable on mdl_dialog_sample|ReflectableTransformed threw error: *** Unfortunately, this feature has not yet been implemented: Attempt to generate code for an unsupported kind of type (LambdaContext) → Object.
    If you wish to ensure that it is prioritized, please report it on github.com/dart-lang/reflectable.
    package:reflectable/src/incompleteness.dart 41                unimplementedError
    package:reflectable/src/transformer_implementation.dart 1452  _ReflectorDomain._typeCodeOfTypeArgument.fail
    package:reflectable/src/transformer_implementation.dart 1479  _ReflectorDomain._typeCodeOfTypeArgument
    package:reflectable/src/transformer_implementation.dart 1471  _ReflectorDomain._typeCodeOfTypeArgument.<fn>
    dart:_internal/iterable.dart 413                              MappedListIterable.elementAt
    dart:_internal/iterable.dart 155                              ListIterable.join
    package:reflectable/src/transformer_implementation.dart 1472  _ReflectorDomain._typeCodeOfTypeArgument
    package:reflectable/src/transformer_implementation.dart 1503  _ReflectorDomain._typeCodeOfClass
    package:reflectable/src/transformer_implementation.dart 894   _ReflectorDomain._generateCode.<fn>.<<fn>_sync_body>.<fn>
    dart:_internal/iterable.dart 390                              MappedIterator.moveNext
    dart:core-patch/core_patch.dart 54                            _SyncIterator.moveNext
    dart:core/iterable.dart 311                                   Iterable.join
    package:reflectable/src/transformer_implementation.dart 3551  _formatAsList
    package:reflectable/src/transformer_implementation.dart 898   _ReflectorDomain._generateCode
    package:reflectable/src/transformer_implementation.dart 127   ReflectionWorld.generateCode.<fn>
    dart:_internal/iterable.dart 413                              MappedListIterable.elementAt
    dart:_internal/iterable.dart 148                              ListIterable.join
    package:reflectable/src/transformer_implementation.dart 3558  _formatAsMap
    package:reflectable/src/transformer_implementation.dart 125   ReflectionWorld.generateCode
    package:reflectable/src/transformer_implementation.dart 3207  TransformerImplementation._generateNewEntryPoint
    package:reflectable/src/transformer_implementation.dart 3350  TransformerImplementation.apply.<async>
    dart:async/zone.dart 1149                                     _RootZone.runUnary
    dart:async/future_impl.dart 502                               _Future._propagateToListeners.handleValueCallback
    dart:async/future_impl.dart 585                               _Future._propagateToListeners
    dart:async/future_impl.dart 376                               _Future._completeWithValue
    dart:async/future_impl.dart 430                               _Future._asyncComplete.<fn>
    dart:async/schedule_microtask.dart 43                         _microtaskLoop
    dart:async/schedule_microtask.dart 52                         _microtaskLoopEntry
    dart:isolate-patch/isolate_patch.dart 96                      _runPendingImmediateCallback
    dart:isolate-patch/isolate_patch.dart 151                     _RawReceivePortImpl._handleMessage
    
    package:reflectable/src/incompleteness.dart 41                unimplementedError
    package:reflectable/src/transformer_implementation.dart 1452  _ReflectorDomain._typeCodeOfTypeArgument.fail
    package:reflectable/src/transformer_implementation.dart 1479  _ReflectorDomain._typeCodeOfTypeArgument
    package:reflectable/src/transformer_implementation.dart 1471  _ReflectorDomain._typeCodeOfTypeArgument.<fn>
    dart:_internal                                                ListIterable.join
    package:reflectable/src/transformer_implementation.dart 1472  _ReflectorDomain._typeCodeOfTypeArgument
    package:reflectable/src/transformer_implementation.dart 1503  _ReflectorDomain._typeCodeOfClass
    package:reflectable/src/transformer_implementation.dart 894   _ReflectorDomain._generateCode.<fn>.<<fn>_sync_body>.<fn>
    dart:core                                                     Iterable.join
    package:reflectable/src/transformer_implementation.dart 3551  _formatAsList
    package:reflectable/src/transformer_implementation.dart 898   _ReflectorDomain._generateCode
    package:reflectable/src/transformer_implementation.dart 127   ReflectionWorld.generateCode.<fn>
    dart:_internal                                                ListIterable.join
    package:reflectable/src/transformer_implementation.dart 3558  _formatAsMap
    package:reflectable/src/transformer_implementation.dart 125   ReflectionWorld.generateCode
    package:reflectable/src/transformer_implementation.dart 3207  TransformerImplementation._generateNewEntryPoint
    package:reflectable/src/transformer_implementation.dart 3350  TransformerImplementation.apply.<async>
    
    opened by MikeMitterer 14
  • 【macos】Attempt to `invoke` without class mirrors.

    【macos】Attempt to `invoke` without class mirrors.

    Flutter 3.3.6 • channel stable • https://github.com/flutter/flutter.git Framework • revision 6928314d50 (3 days ago) • 2022-10-25 16:34:41 -0400 Engine • revision 3ad69d7be3 Tools • Dart 2.18.2 • DevTools 2.15.0

    [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: *** Unexpected situation encountered! Please report a bug on github.com/dart-lang/reflectable: Attempt to invoke without class mirrors. #0 unreachableError (package:reflectable/src/incompleteness.dart:30:3) #1 _InstanceMirrorImpl.invoke (package:reflectable/src/reflectable_builder_based.dart:260:13) #2 ModuleManager.invoke (package:plugin_ffi_engine/ajx/modules/ModuleManager.dart:122:34) #3 JsContext.invoke (package:plugin_ffi_engine/ajx/JsContext.dart:97:19) #4 NativeModuleDefinition_call (package:plugin_ffi_engine/ajx/core/native_module_definition.dart:24:13) #5 MessageNativeModuleCall.call (package:plugin_ffi_engine/amap_ffi_msg_native_module.dart:16:7) #6 MainIsolateMsgListener.listen. (package:plugin_ffi_engine/amap_ffi_msg_listener.dart:44:14) #7 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10) #8 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11) #9 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #10 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19) #11 _StreamController._add (dart:async/stream_controller.dart:648:7) #12 _StreamController.add (dart:async/stream_controller.dart:596:5) #13 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

    bug 
    opened by anql 1
  • Get annotation from enum field

    Get annotation from enum field

    My goal is to create a Description annotation for enums (something like "DescriptionAttribute" that exists on C#). I try the code below but the "metadata" returns always empty.

    class Description {
      const Description(this.value);
    
      final String value;
    }
    
    @reflector
    enum Example {
      @Description("A")
      a,
      @Description("B")
      b
    }
    
    
    void main() {
      initializeReflectable();
    
      var val = Example.a;
      var instanceMirror = reflector.reflect(val);
      var variableMirror = instanceMirror.type.declarations[val.name] as VariableMirror;
      print(variableMirror.metadata.length); // 0
    }
    

    But if I replace the enum for a class, it works perfectly.

    class Description {
      const Description(this.value);
    
      final String value;
    }
    
    @reflector
    class Example {
      const Example(this.a);
    
      @Description("a")
      final String a;
    }
    
    
    void main() {
      initializeReflectable();
    
      var val = const Example("A");
      var instanceMirror = reflector.reflect(val);
      var variableMirror = instanceMirror.type.declarations["a"] as VariableMirror;
      print(variableMirror.metadata.length); // 1
    }
    

    Am I doing something wrong or is there another way to achieve this objective? Or should I use dart:mirrors directly?

    opened by lucas404x 2
  • Add support for generic type arguments in annotations

    Add support for generic type arguments in annotations

    Overview

    Adds support for generic annotations, a feature added in Dart SDK 2.14.

    Take this class for example:

    @reflector
    class Person {
      @TypeHelper<Soul>(42, "The meaning")
      String? life;
    }
    
    class TypeHelper<T> {
      const TypeHelper(int var1, String var2);
    }
    
    class Soul { }
    

    The annotation would have previously been identified as having the type argument dynamic:

    ClassMirror personClassMirror = reflector.reflectType(Person) as ClassMirror;
    VariableMirror field = personClassMirror.declarations["life"] as VariableMirror;
    var annotation = field.metadata[0];
    print(annotation.runtimeType); // TypeHelper<dynamic>
    

    It will now be correctly identified as having the type argument Soul:

    print(annotation.runtimeType); // TypeHelper<Soul>
    

    This is done by appending the type arguments (if any exist) after the annotation name during the _extractMetadataCode function of builder_implementation.dart.

    opened by jacksonjude 5
  • Inconsistency with both typeAnnotationQuantifyCapability and superclassQuantifyCapability

    Inconsistency with both typeAnnotationQuantifyCapability and superclassQuantifyCapability

    When using the two capabilities typeAnnotationQuantifyCapability and superclassQuantifyCapability combined, the covered reflectable classes are not as expected.

    Type annotations from super classes are reflectable, but super classes of type annotations are not. According to the code documentation, my expectation is, that in both cases all classes must be reflectable.

    Consider the following Reflector:

    class Reflector extends Reflectable {
      const Reflector()
          : super(instanceInvokeCapability, reflectedTypeCapability,
                typeAnnotationQuantifyCapability, superclassQuantifyCapability);
    }
    const reflector = Reflector();
    

    In the following case, the annotated class A extends a class B which has a class member of type C. In this case, all classes A, B and C are reflectable, which is what I expect.

    @reflector
    class A extends B { }
    
    class B {
      C? c;
    }
    
    class C {}
    

    The second case is the other way around, the annotated class A has a member of type B which extends class C. In this case, only class A and B are reflectable.

    @reflector
    class A {
     B? b;
    }
    
    class B extends C {}
    
    class C {}
    

    My expectation is that class C must be reflectable as well, since the doc of superclassQuantifyCapability is:

    Gives support for reflection on all superclasses of covered classes.

    opened by Dimibe 0
  • InstanceInvokeCapability only for getters and setters

    InstanceInvokeCapability only for getters and setters

    Im not sure what it's invoking nor do i know how to use the regex filter on InstanceInvokeCapability. Just need the getters and setters for field declarations.

    opened by cyberpwnn 1
  • Extend README.md to cover more cases

    Extend README.md to cover more cases

    Cf. https://github.com/google/reflectable.dart/issues/263#issuecomment-1043746185 and https://github.com/google/reflectable.dart/issues/263#issuecomment-1044193588: README.md ought to give more examples and mention more properties of reflectable. E.g., that there is no need for a class with reflection to depend on anything in reflectable.

    enhancement documentation 
    opened by eernstg 0
Owner
Google
Google ❤️ Open Source
Google
This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Alexander Mazuruk 348 Nov 22, 2022
Dependency Injection is a great design pattern that allows us to eliminate rigid dependencies between elements and it makes the application more flexible

GetX lib DI pattern Dependency Injection is a great design pattern that allows us to eliminate rigid dependencies between elements and it makes the ap

Trương Việt Hoàng 4 Feb 1, 2022
null 2 Apr 17, 2022
Library for help you make userbot or bot telegram and support tdlib telegram database and only support nodejs dart and google-apps-script

To-Do telegram client dart ✅️ support multi token ( bot / userbot ) ✅️ support bot and userbot ✅️ support telegram-bot-api local server ✅️ support tel

Azka Full Snack Developer:) 63 Nov 9, 2022
A configurable pattern finder for static analysis written in Dart

mistdumper A configurable pattern finder for static analysis written in Dart. It is meant to retrieve offsets from file on disk without running them.

null 3 Sep 12, 2022
An application built using Flutter that holds a static personal/professional informations related to me in the form of card.(Digital Visiting Card)

mi_card_flutter A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

dev_allauddin 3 Feb 3, 2022
A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

DotCoder 1 Aug 23, 2022
Show dynamic operation in Stateful Widget in Flutter

A new Flutter project. It will count the number of donut.

Avinandan Bose 1 Mar 15, 2022
The `TypedEventNotifier` library allows notifying listeners with an object.

The TypedEventNotifier library allows notifying listeners with an object. listeners can be subscribed to only a special type or group of objects.

Evgeniy Ilyin 0 Nov 13, 2021
An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Leynier Gutiérrez González 7 Aug 24, 2022
VS Code `.code-workspace` file generator

VS Code .code-workspace file generator (for monorepositories with Dart and Flutter projects) TL;DR; Create yaml file config.yaml (check #Format sectio

Mike T 1 Feb 18, 2022
A Gura parser implementation for Dart

Gura Dart parser This repository contains the implementation of a Gura configuration format parser for Dart, written in pure Dart. (Compliant with spe

Zack Campbell 4 Aug 2, 2021
A pure Dart implementation of the Pusher Channels Client

pusher_channels is a pure Dart pusher channels client. This client is work in progress and it is unstable. Usage A simple usage example: import 'packa

Indaband 7 Nov 6, 2022
Reference implementation for the Zenon SDK for Dart and Flutter apps compatible

Zenon Dart SDK Reference implementation for the Zenon SDK for Dart and Flutter apps compatible with the Zenon Alphanet - Network of Momentum Phase 0.

null 8 Nov 23, 2022
A Dart package to web scraping data from websites easily and faster using less code lines.

Chaleno A flutter package to webscraping data from websites This package contains a set of high-level functions that make it easy to webscrap websites

António Nicolau 27 Nov 17, 2022
Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Kinnara Digital Studio 0 Oct 27, 2021
Flutter implementation of Clean Architecture, inspired on the guidelines created by Uncle Bob.

clean_framework Flutter implementation of Clean Architecture, inspired on the guidelines created by Uncle Bob. see http://www.amazon.com/dp/0134494164

Acme Software 18 Oct 23, 2022
Flutter's sync log component implementation by DartNative.

Flutter's sync log component implementation by DartNative

DartNative 3 Apr 30, 2022
🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

Flutter Gen Zeplin Extension ?? The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time. ⬇ 1.1k Getti

NAVER 49 Oct 12, 2022