0

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;
    });
  }
leftjoin
  • 36,950
  • 8
  • 57
  • 116
  • Probably you need to set up your class with a TypeAdapter. https://docs.hivedb.dev/#/custom-objects/generate_adapter – Csisanyi Sep 16 '21 at 23:10
  • Can you post more complete code (ideally a minimal, reproducible example)? Where is `attributeSelect` declared? – jamesdlin Sep 16 '21 at 23:35
  • The typeadapter is set up for test, etc. As I said it works fine if I write myBox.getAt(i).test, but writing myBox.getAt(i).attributeSelect with attributeSelect = test doesn't work because it doesn't use the value of that variable. – spikelucky Sep 17 '21 at 14:11
  • I see what you're trying to do now: you want to use a `String` as a property name. That's not possible without code generation. Alternatively you could store a `Map`. – jamesdlin Sep 17 '21 at 20:01
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 24 '21 at 10:53

1 Answers1

0

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));
              }...
  • Even with the 100s of if-clauses it still runs in a split second. It was just annoying to program that way. Hopefully isar will be working properly soon and we won't need to program our own queries. Until then this works well enough. – spikelucky Sep 17 '21 at 16:13