Flutter future Boolean function always return default value

1.2k views Asked by At

I have a Future boolean function in that function I checked some data using the map function. if and else both conditions set the boolean variable is true. but it always returns the default false value. below code is my function.

  Future<bool> checkisShowablebydepend(Questions questions) async {
    bool isDependvalue = false;

    questions.dependFields.map((e) async {
      bool isequal = (questions.dependValue.toLowerCase() ==
          _formKey.currentState.fields[e].value.toLowerCase());

      if (isequal) {
        isDependvalue = true;
      } else {
        isDependvalue = true;
      }
    });

    return isDependvalue;
  }

here this is how i got data from above function.

  Widget loadWidgets(Questions questions) {
    if (questions.depend) {
      return FutureBuilder<bool>(
          future: checkisShowablebydepend(questions),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return new Text('Press button to start');
              case ConnectionState.waiting:
                return new Text('Awaiting result...');
              default:
                if (snapshot.hasError)
                  return new Text('Error: ${snapshot.error}');
                else
                  return new Text('Result: ${snapshot.data}');
            }
          });
    } else {
      return selectFormfield(questions);
    }
  }
2

There are 2 answers

0
Tom Rivoire On

If your goal is to iterate trough your questions.dependFields list, then forEach seems more appropriate.

I'm not sure that this functions needs to be Future by the way.

0
Mittal Varsani On

Async means that this function is asynchronous and you might need to wait a bit to get its result.

Await means - wait here until this function is finished and you will get its return value.

The await keyword only works within an async function.

You have set the function as sync so you can use await keyword to wait for the comparison result

questions.dependFields.map((e) async {
      bool isequal = await (questions.dependValue.toLowerCase() ==
          _formKey.currentState.fields[e].value.toLowerCase());

      if (isequal) {
        isDependvalue = true;
      } else {
        isDependvalue = true;
      }
    });