Allows Dart reflection using code generation/builder.

Overview

reflection_factory

pub package Null Safety Codecov CI GitHub Tag New Commits Last Commits Pull Requests Code size License

reflection_factory allows Dart reflection with an easy approach, even for third-party classes, using code generation portable for all Dart platforms.

Usage

To enable/generate reflection for some class/type, you can use two approaches:

  • @EnableReflection():

    Annotation that indicates that a specific class/type will have reflection.

  • @ReflectionBridge([User, Profile]):

    Annotation that indicates through a bridge class that the types (User and Profile) will have reflection.

@EnableReflection

The annotations @EnableReflection is used above your class/type that you want to have reflection enabled.

File: some_source_file.dart:

import 'package:reflection_factory/reflection_factory.dart';

// Add a reference to the code generated by:
// $> dart run build_runner build
part 'some_source_file.reflection.g.dart';

// Indicates that reflection for class `User` will be generated/enabled:
@EnableReflection()
class User {
  String? email;

  String pass;

  User(this.email, this.pass);

  User.empty() : this(null,'') ;

  bool get hasEmail => email != null;

  bool checkPassword(String pass) {
    return this.pass == pass;
  }
}

void main() {
  var user = User('[email protected]', '123');

  // The generated reflection:
  var userReflection = user.reflection;

  var fieldEmail = userReflection.field('email')!;
  print('email: ${fieldEmail.get()}');

  var methodCheckPassword = userReflection.method('checkPassword')!;

  var passOk1 = methodCheckPassword.invoke(['wrong']); // false
  print('pass("wrong"): $passOk1');

  var passOk2 = methodCheckPassword.invoke(['123']); // true
  print('pass("123"): $passOk2');

  // Using the generated `toJson` extension method:
  print('User JSON:');
  print(user.toJson());

  // Using the generated `toJsonEncoded` extension method:
  print('User JSON encoded:');
  print(user.toJsonEncoded());
  
  // Accessing reflection through class:
  var userReflection2 = User$reflection();

  // Creating an `User` instance from default or empty constructor:
  var user2 = userReflection2.createInstance()!;

  user2.email = '[email protected]';
  user2.pass = 'abc';

  print('User 2 JSON:');
  print(user2.toJson());
  
}

OUTPUT:

email: [email protected]
pass("wrong"): false
pass("123"): true
User JSON:
{email: [email protected], hasEmail: true, pass: 123}
User JSON encoded:
{"email":"[email protected]","hasEmail":true,"pass":"123"}
User 2 JSON:
{email: [email protected], hasEmail: true, pass: abc}

@ReflectionBridge

The annotations @ReflectionBridge is used above a bridge class, and indicates that third-party types will have reflection generated.

File: some_source_file.dart:

import 'package:reflection_factory/reflection_factory.dart';

// Class `User` is from a third-party package:
import 'package:some_api/user.dart';

// Add a reference to the code generated by:
// $> dart run build_runner build
part 'some_source_file.reflection.g.dart';

// Indicates that reflection for class `User` will be generated/enabled
// through a bridge class:
@ReflectionBridge([User])
class UserReflectionBridge {}

void main() {
  var user = User('[email protected]', '123');

  // The generated reflection through bridge class:
  var userReflection = UserReflectionBridge().reflection(user);

  var fieldEmail = userReflection.field('email')!;
  print('email: ${fieldEmail.get()}');

  print('User JSON encoded:');
  print(user.toJsonEncoded());
}

OUTPUT:

email: [email protected]
User JSON encoded:
{"email":"[email protected]","pass":"123","hasEmail":true}

Dependencies

You need to add 2 dependencies in your project:

File: pubspec.yaml

dependencies:
  reflection_factory: ^1.0.0

dev_dependencies:
  build_runner: ^2.1.1

Building/Generating Code

To generate the reflection code just run build_runner in your Dart project:

$> dart run build_runner build

Source

The official source code is hosted @ GitHub:

Features and bugs

Please file feature requests and bugs at the issue tracker.

Contribution

Any help from the open-source community is always welcome and needed:

  • Found an issue?
    • Please fill a bug report with details.
  • Wish a feature?
    • Open a feature request with use cases.
  • Are you using and liking the project?
    • Promote the project: create an article, do a post or make a donation.
  • Are you a developer?
    • Fix a bug and send a pull request.
    • Implement a new feature.
    • Improve the Unit Tests.
  • Have you already helped in any way?
    • Many thanks from me, the contributors and everybody that uses this project!

If you donate 1 hour of your time, you can contribute a lot, because others will do the same, just be part and start with your 1 hour.

Author

Graciliano M. Passos: gmpassos@GitHub.

License

Apache License - Version 2.0

Comments
  • v1.2.13

    v1.2.13

    • Json:
      • Add parameter TypeInfo as an alternative to the parameter Type.
      • Improve collections casting.
    • TypeInfo:
      • Added constructors: TypeInfo.fromListType, TypeInfo.fromSetType, TypeInfo.fromMapType.
      • Added toListType, toSetType, toIterableType, toMapValueType and toMapKeyType.
      • Added castList, castSet, castIterable and castMap.
    opened by gmpassos 2
  • Upgrade analyzer dependency for compatibility with newer packages

    Upgrade analyzer dependency for compatibility with newer packages

    Trying to use reflection factory with other packages causes conflict in getting dependencies (e.g. flutter_data: ^1.4.4)

    flutter pub get

    Because reflection_factory <1.0.24 depends on analyzer ^2.1.0 and reflection_factory >=1.0.24 <1.1.1 depends on analyzer ^3.3.1, reflection_factory <1.1.1 requires analyzer ^2.1.0 or ^3.3.1.
    And because reflection_factory >=1.1.1 depends on analyzer ^3.4.1, every version of reflection_factory requires analyzer ^2.1.0 or >=3.3.1 <4.0.0.
    Because no versions of flutter_data match >1.4.4 <2.0.0 and flutter_data 1.4.4 depends on analyzer ^4.1.0, flutter_data ^1.4.4 requires analyzer ^4.1.0.
    Thus, flutter_data ^1.4.4 is incompatible with reflection_factory.
    So, because scout_core depends on both flutter_data ^1.4.4 and reflection_factory any, version solving failed.
    pub get failed (1; So, because scout_core depends on both flutter_data ^1.4.4 and reflection_factory any, version solving failed.)
    

    Is upgrading the dependency possible?

    opened by alguintu 2
  • v1.2.8

    v1.2.8

    • FunctionReflection.methodInvocationFromMap and FunctionReflection.methodInvocation:
      • Better handling of unresolved parameters values. Attempts to resolve 2 times, to allow entities references through cache.
    • Reflection:
      • castList, castSet, castIterable, castMap, castCollection:
        • Added parameter nullable.
    opened by gmpassos 1
  • v1.2.7

    v1.2.7

    • TypeInfo:
      • Added T generic type.
      • Added callCasted to pass the T to a Function<T>().
      • Improved internal representation og arguments.
    • ReflectionBuilder:
      • Declare reflected types using TypeInfo<T> generics.
    opened by gmpassos 1
  • Not an issue, so much as some questions

    Not an issue, so much as some questions

    I saw your reference to reflection_factory in a thread about the dart:mirror module. I have two questions:

    1. can reflection_factory be used as a replacement for json_serializable?
    2. if yes, will "dart compile exe" fail if I use your reflection_factory the way it does when using json_serializable?
    3. if no, (I doubt this) could importing reflection_factory, cause json_serializable to no longer cause this compilation issue?

    You can see my use case in a comment below yours.

    Thanks

    question 
    opened by labaxter 1
  • v1.0.20

    v1.0.20

    • Added TypeInfo to perform type checking and handle other Type operations needed for reflection use.
    • Improved TypeReflection for Function types.
    • Fixed constructors with nullable named parameters.
    • Fixed constructors with required named parameters.
    • Fixed fields/parameters with Function typedef alias.
    opened by gmpassos 1
  • [Question] Intercepting to Method invocation

    [Question] Intercepting to Method invocation

    Following up on the discussion -> https://github.com/google/reflectable.dart/issues/301#issuecomment-1338130765

    I am wondering how I can use reflection_factory to accomplish this. Are you able to provide some code examples?

    Client Code:

    @Component()
    class MyWidget extends StatelessWidget {
    
     @override
      State<MyWidget> createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      @override
       void dispose() {                 <-------<< // I want to do something when before this method is called.
    
       }
    }
    
    opened by dinbtechit 7
Releases(1.2.17)
Owner
Graciliano Monteiro Passos
Graciliano Monteiro Passos
Code generation for immutable classes that has a simple syntax/API without compromising on the features.

Welcome to Freezed, yet another code generator for unions/pattern-matching/copy. 0.14.0 and null-safety Important note: From 0.14.0 and onwards, Freez

Remi Rousselet 1.4k Jan 4, 2023
The next-generation cross-platform Minecraft Launcher.

MultiFold MultiFold is the next-generation cross-platform Minecraft launcher. This project is currently work-in-progress. Contributing You are welcome

MultiFold 29 Nov 9, 2022
Item selling mobile app with secure payments with Payhere payment gateway. Auto APK generation with github actions CI/CD.

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

Shihara Dilshan 2 Jan 20, 2022
A StreamBuilder alternative that provides builder and event callbacks

mainstream A StreamBuilder alternative that provides builder and event callbacks. See the Futuristic package for a similar API for working with Future

Martin Rybak 6 Apr 9, 2021
Utility Manager Flutter Application is made with Flutter and Supabase which allows user to add task, set remainder to the task, set color to separate tasks and it allows to add URL with URL's informations.

Utility Manager Flutter Application! Utility Manager Flutter Application is made with Flutter and Supabase which allows user to add task, set remainde

Kathirvel Chandrasekaran 6 Jan 6, 2022
A collection of Dart code samples by Dart DevRel

Dart samples A collection of Dart programs that illustrate features and best practices. For a list of community-maintained projects, see Awesome Dart.

Dart 458 Dec 30, 2022
A discord bot, made with Dart, which lets you run your own pure Dart code snippets directly via a discord ping, and get the output in an instant.

A discord bot, made with Dart, which lets you run your own pure Dart code snippets directly via a discord ping, and get the output in an instant.

Anikate De 3 Oct 21, 2022
Quiz App is cross-platform mobile app, that allows you to test your knowledge on various technologies through quizzes. It's built with Flutter & Dart

Quiz App is cross-platform mobile app, that allows you to test your knowledge on various technologies through quizzes. It's built with Flutter & Dart

Régis 6 Sep 19, 2022
UI design for mobile, create using visual studio code & flutter dart programming languange

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

null 1 Oct 13, 2021
A multiplatform Dart movie app with 40% of code sharing between Flutter and the Web.

A multiplatform Dart movie app with 40% of code sharing between Flutter and the Web.

Iiro Krankka 3.4k Dec 30, 2022
Utilities for loading and running WASM modules from Dart code

Provides utilities for loading and running WASM modules Built on top of the Wasmer runtime. Setup Run dart run wasm:setup to build the Wasmer runtime.

Dart 284 Dec 23, 2022
Routinger is a task scheduler app that is made to make you a better person at no extra cost. The code is open-source. Dart language and Flutter framework are used extensively.

Routinger This is a simple app that will allow you to schedule your tasks, create a simple to-do, and also make recurring tasks. The app ends you noti

Routinger 16 Dec 17, 2022
Dart GraphQL server implementation. Utilities, code generator, examples and reference implementation.

Leto - GraphQL Server A complete implementation of the official GraphQL specification in the Dart programming language. Inspired by graphql-js, async-

Juan Manuel Castillo 29 Nov 27, 2022
Flutter plugin that allows users to create TextAvatar easily!

Colorize Text Avatar Colorize Text Avatar is a package to generate avatar based on your user initials. It supports to generate avatars based on your s

Deniz Çolak 17 Dec 14, 2022
FileManager is a wonderful widget that allows you to manage files and folders, pick files and folders, and do a lot more. Designed to feel like part of the Flutter framework.

File Manager FileManager is a wonderful widget that allows you to manage files and folders, pick files and folders, and do a lot more. Designed to fee

Devs On Flutter 52 Dec 30, 2022
Sample Flutter Drawing App which allows the user to draw onto the canvas along with color picker and brush thickness slider.

DrawApp Sample Flutter Drawing App which allows the user to draw onto the canvas along with color picker and brush thickness slider. All code free to

Jake Gough 226 Nov 3, 2022
This plugin allows Flutter desktop apps to resizing and repositioning the window.

window_manager This plugin allows Flutter desktop apps to resizing and repositioning the window. window_manager Platform Support Quick Start Installat

LeanFlutter 346 Jan 3, 2023
This plugin allows Flutter desktop apps to defines system/inapp wide hotkey (i.e. shortcut).

hotkey_manager This plugin allows Flutter desktop apps to defines system/inapp wide hotkey (i.e. shortcut). hotkey_manager Platform Support Quick Star

LeanFlutter 81 Dec 21, 2022
A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a discord bot. It can link multiple farmers/harvesters to your account.

farmr A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a di

Gil Nobrega 261 Jan 2, 2023