skip to Main Content

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


  1. 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 the dart: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:

    import 'package:flutter/material.dart';
    import 'package:dart/mirrors.dart';
    
    void main() {
      // Define your variable
      String foodIcon = 'assets/icons/expense/food.png';
    
      // Use reflection to get the variable name as a string
      dynamic mirror = Mirror(reflect([foodIcon]));
      String variableName = mirror.getField(#name).toString();
    
      print(variableName); // Output: foodIcon
    }
    
    Login or Signup to reply.
  2. This can not be achieved in dart, it will create problems for tree shaking.

    You can refer this article as well

    Login or Signup to reply.
  3. import 'dart:mirrors';
    
    String getVariableName(Object variable, Map<dynamic, String> variables) {
      var entry = variables.entries.firstWhere(
        (entry) => entry.key == variable,
        orElse: () => null,
      );
    
      return entry?.value;
    }
    
    void main() {
      // Define your variables
      int myVar1 = 42;
      double myVar2 = 3.14;
      String myVar3 = 'Hello';
    
      // Create a map associating variables with their names
      var variableNames = {
        myVar1: 'myVar1',
        myVar2: 'myVar2',
        myVar3: 'myVar3',
      };
    
      // Use the function to get the variable name as a String
      String name = getVariableName(myVar2, variableNames);
    
      // Print the result
      print('Variable name: $name'); // Output: Variable name: myVar2
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search