use reflection In flutter #333
Unanswered
chamodyauthpalabandara
asked this question in
Q&A
Replies: 1 comment
-
You can certainly do that. Here's an example: // ----- Library 'main.dart'.
import 'package:reflectable/reflectable.dart';
import 'main.reflectable.dart';
class Reflector extends Reflectable {
const Reflector() : super(subtypeQuantifyCapability, newInstanceCapability);
}
const reflector = Reflector();
@reflector
abstract class ISyncService {
Future fetchAndSyncData();
}
void main() {
initializeReflectable();
for (var classMirror in reflector.annotatedClasses) {
if (classMirror.simpleName != 'ISyncService') {
dynamic instance = classMirror.newInstance('', const [], const {});
if (instance is ISyncService) {
instance.fetchAndSyncData();
}
}
}
}
// ------------------------------------------------------------
// The classes below could be in other libraries. There is no
// need for 'main.dart' to contain a complete list of subtypes
// of `ISyncService` in any way, they will be included in
// `reflector.annotatedClasses` because `reflector` has the
// capability `subtypeQuantifyCapability`.
class InvoiceSyncService implements ISyncService {
@override
Future<void> fetchAndSyncData() async {
// Implementation for syncing invoices
print('Syncing invoices...');
// Perform sync logic here
}
}
class ProductSyncService implements ISyncService {
@override
Future<void> fetchAndSyncData() async {
// Implementation for syncing products
print('Syncing products...');
// Perform sync logic here
}
} Note that reflectable is based on code generation, and you need to perform the code generation starting from the entry point of the application that you want to cover (that is, the library that contains the
Things will be slightly different when in Flutter, but I used plain Dart in order to make the example as simple as possible. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
In the Flutter application, I use the interface class to implement the methods and in the main class I need to find dynamically classes that were implemented using the ISyncService interface and execute all of them
here is an example of a classes
abstract class ISyncService {
Future fetchAndSyncData();
}
class InvoiceSyncService implements ISyncService {
@OverRide
Future fetchAndSyncData() async {
// Implementation for syncing invoices
print('Syncing invoices...');
// Perform sync logic here
}
}
class ProductSyncService implements ISyncService {
@OverRide
Future fetchAndSyncData() async {
// Implementation for syncing products
print('Syncing products...');
// Perform sync logic here
}
}
Can I use reflection to achieve this, like I do with other languages (.net, java)?
if it can't can you suggest some method to achieve this task?
Beta Was this translation helpful? Give feedback.
All reactions