How to await a listener being called and return a Future value

733

Ok I found a solution that works in this case is to use Completer() as follows:

  Map<String,ValueNotifier<String>> _data = {};

  Future<String> getAnswer(String text) async {
    var completer = Completer<String>();
    if (_data["answer"] == null || _data["answer"]!.value.isEmpty) {
      _data["answer"] = ValueNotifier<String>("");

      _data["answer"]!.addListener(() {
        if (_data["answer"]!.value.isNotEmpty) {
          completer.complete(_data["answer"]!.value);
          _data["answer"]!.dispose();
        }
      });

    } else {
      return _data["answer"]!.value;
    }

    return completer.future;
  }
Share:
733
Mijawel
Author by

Mijawel

Updated on January 03, 2023

Comments

  • Mijawel
    Mijawel over 1 year

    I have a Future function which adds a listener to a ValueNotifier. How can I return a value that I retrieve when the listener is called?

      Map<String,ValueNotifier<String>> _data = {};
    
      Future<String> getAnswer(String text) async {
        if (_data["answer"] == null || _data["answer"]!.value.isEmpty) {
          _data["answer"] = ValueNotifier<String>("");
    
          _data["answer"]!.addListener(() {
            if (_data["answer"]!.value.isNotEmpty) {
              // somehow return _data["answer"]!.value
            } else {
              // continue waiting for next listener call
            }
          });
    
        } else {
          return _data["answer"]!.value;
        }
    
        return await //not sure what to put here.
      }
    
    • Chinmay Kabi
      Chinmay Kabi about 2 years
      I have a feeling whatever you are trying to achieve here can be done more elegantly. Could you specify what are you trying to do here?
    • Mijawel
      Mijawel about 2 years
      I'm trying to have a Future function basically listen to a value and return that value when it is updated.
    • Chinmay Kabi
      Chinmay Kabi about 2 years
      I don't understand why you want the listener inside a future. You can attach the listener inside any function right
    • Mijawel
      Mijawel about 2 years
      In theory yes, but it would make the code a lot messier. I have actually done something very similar with a Stream function and a stream controller where the listener adds an event to the stream controller which yields the value in the stream function. I just assumed there would be a similar solution for futures (which in essence is just a stream function that only yields a single value right?)