String foodIcon = 'assets/icons/expense/food.png';
I want to receive the foodIcon variable name as a String value (‘foodIcon’)
I saw a StackOverflow answer for a similar question that says to use a map or dictionary.
Is there any method to do this?
Thanks in advance.
3
Answers
Yes, you can achieve this by using a technique called "reflection" in Dart. Reflection allows you to inspect and manipulate the properties and methods of an object at runtime. In your case, you can use the
Mirror
class from thedart:mirrors
library to reflect on the variables defined in your code and retrieve their names as strings.First, you need to add the
dart:mirrors
library to your project.Here’s an example of how you could do it:
This can not be achieved in dart, it will create problems for tree shaking.
You can refer this article as well