Issue
What is the most efficient way of getting the symbol for a single member of a class?
import 'dart:mirrors';
class TestClass{
void iWantThisSymbol(){}
void butNotThisOne(){}
}
/**
* I can get all the symbols and filter down but this isn't nice
*/
void main(){
var allSymbols = reflectClass(TestClass).instanceMembers.keys;
var justTheSymbolIWant = allSymbols.where((symbol) => symbol.toString().contains('iWantThisSymbol')); // this doesnt seem very efficient or maintainable
}
Solution
var justTheSymbolIWant = reflectClass(TestClass).instanceMembers[#iWantThisSymbol]
Although, to be a bit pedantic, you’re not get getting a Symbol, you’re using a Symbol (#iWantThisSymbol
) to get a member, which in this case is a method. So I would rewrite this as:
import 'dart:mirrors';
class TestClass{
void iWantThisMethod(){}
void butNotThisOne(){}
}
void main(){
var justTheMethodIWant = reflectClass(TestClass).instanceMembers[#iWantThisMethod];
}
Also, a few things about that use of where()
:
- If you do want to filter a list of Symbols, you don’t need to them convert to a String, you can just compare symbol instances directly.
.where()
returns an iterable, even if there’s only one item that matches. You probably wantfirstWhere()
which always returns a single item.
var justTheSymbolIWant = allSymbols.firstWhere((symbol) => symbol == #iWantThisSymbol);
Answered By – Justin Fagnani
Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)