Home > OS >  How to use a variable for method name
How to use a variable for method name

Time:09-28

I want to use a variable to access a certain value in my hive database: In the code below if I use myBox.getAt(i).attributeSelect I get an error because attributeSelect is not defined for the box. If I use myBox.getAt(i).test it works. How can I make flutter recognise that attributeSelect is a variable and put the value there? I have a total of 181 different variables the user can choose from. Do I really need that many if clauses? The variables are booleans. So I want to check if that attribute is true for the document at index i.

Error: NoSuchMethodError: 'attributeSelect' method not found Receiver: Instance of 'HiveDocMod'

attributeSelect = 'test'; //value depends on user choice
Future<void> queryHiveDocs() async {
    final myBox = await Hive.openBox('my');
    for (var i = 0; i < myBox.length; i  ) {
      if (attributeSelect == 'All Documents') {
        _hiveDocs.add(myBox.getAt(i)); // get all documents
        //print(myBox.getAt(24).vesselId);
      } else {
        // Query for attribute
        if (myBox.getAt(i).attributeSelect) {
          _hiveDocs.add(myBox.getAt(i)); // get only docs where the attributeSelect is true
        }
      }
    }
    setState(() {
      _hiveDocs = _hiveDocs;
      _isLoading = false;
    });
  }

CodePudding user response:

I solved it the annoyingly hard way:

            if (attributeSelect == 'crsAirCompressor') {
              if (myBox.getAt(i).crsAirCompressor) {
                _hiveDocs.add(myBox.getAt(i));
              }
            } else if (attributeSelect == 'crsBatteries') {
              if (myBox.getAt(i).crsBatteries) {
                _hiveDocs.add(myBox.getAt(i));
              }...
  • Related