Home > Blockchain >  How can I access the value of a variable in Dart(Flutter)
How can I access the value of a variable in Dart(Flutter)

Time:08-29

I have a variable which was declared initially and which will be changed after a drop down selection. I couldnot access the value after it has been changed by using for loop and c

   String _selectedRegNoUpdate = 'Reg No';
   String _selectedRegNoUpdate1 = 'Reg No';
   String _selectedRegNoUpdate2 = 'Reg No';
   String _selectedRegNoUpdate3 = 'Reg No';
   String _selectedRegNoUpdate4 = 'Reg No';
   String _selectedRegNoUpdate5 = 'Reg No';

 for(int i = item!['workedWith'].length; i < 6 ; i  ){
                                                                                                      
   print(i.toString());                                                                                                        
   String workedWithPosition = '_selectedRegNoUpdate$i';
                                                                                                      
   print(workedWithPosition);  // this prints _selectedRegNoUpdate3
                                                                                                      
   print(_selectedRegNoUpdate4);   // this prints the value which is stored in _selectedRegNoUpdate4 which is 12345
                                                                                                      
   print(workedWithPosition);  //but this print Reg No3 not the value selected by the drop down selector
                                                                                                      
   print((_selectedRegNoUpdate i.toString()).toString());
                                                                                                    
 };

CodePudding user response:

You cannot, in Dart, point to a variable directly based on a String value (unless we use reflection with dart:mirrors which are not supported on lot of platforms).

What you should do instead is create a List<String> which contains your values. This list can you then search using an index number.

List<String> _selectedRegNoUpdate = [
  'Reg No 1',
  'Reg No 2',
  'Reg No 3',
  'Reg No 4',
  'Reg No 5',
  'Reg No 6',
];

void main() {
  for (int i = 0; i < _selectedRegNoUpdate.length; i  ) {
    print(_selectedRegNoUpdate[i]);
  }
}
  • Related