1

I am trying to dynamically retrieve TextControllers text value. I created an object like so:

  final _ingredientsDataMap = {
    'IngredientName': {
      'label': 'Ingredient Name',
      'controller': new TextEditingController(),
    },
    'Amount': {
      'label': 'Amount',
      'controller': new TextEditingController(),
    },
    'Unit': {
      'label': 'Unit',
      'controller': new TextEditingController(),
    },
  };

and a function for testing purposes

  _submitData() {
    for (var k in _ingredientsDataMap.keys) {
      var currentValue = _ingredientsDataMap[k];
      var controller = currentValue!['controller'];
      // Neither way works
      print(controller!['text']);
      print(controller!.text;
    }
  }

However, I get an error as soon as I add text to the end of the controller variable and of course the program will not compile: The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'

What am I doing wrong here? Is my initial map the culprit? I suspect there is something I am missing (I come from a javascript background).

Also including a DartPad implementation that works as long as you comment out the print line: https://dartpad.dev/?id=5969246a632f388bf32e8649620a2c34&null_safety=true

ShowstopperCode1
  • 228
  • 1
  • 4
  • 15

2 Answers2

1

Ok, I was overthinking this, and also had to switch off the Javascript part of my brain. Instead of passing in a label and separate controller, I simplified it to have the label be the key, and the value be the controller.

I am thinking the original issue is due to Dart/Flutter being a typed language?

  final Map<String, TextEditingController> _ingredientsMap = {
    'Ingredient name': new TextEditingController(),
    'Amount': new TextEditingController(),
    'Unit': new TextEditingController(),
  };

Updated DartPad: https://dartpad.dev/?id=5969246a632f388bf32e8649620a2c34&null_safety=true

Also if I wanted to keep the previous implementation, I have to cast the text controller:

    for (var key in _ingredientsMap.keys) {
      var currentValue = _ingredientsMap[key];

      data[key] = (currentValue!['controller'] as TextEditingController).text;
    }
  final _ingredientsMap = {
    'ingredient': {
      'controller': new TextEditingController(),
      'label': 'Ingredient Name',
    },
    'amount': {
      'controller': new TextEditingController(),
      'label': 'Unit',
    },
    'measurement': {
      'controller': new TextEditingController(),
      'label': 'Amount',
    }
  };
ShowstopperCode1
  • 228
  • 1
  • 4
  • 15
-1

TextEditingController() is not a map so you cannot access the values like this, instead, it has properties. you can access the text like this:

controller!.text
Benyamin
  • 1,008
  • 11
  • 18