Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

dart - Return code results after some delay in Flutter?

I'm trying to run this Future function that runs a Timer once 500 milliseconds have passed. The issue I'm having is that the timer is not passing the data to the results variable so the _destinationOnSearchChanged() ends up returning null.

Note: getCity(context, _typeAheadController.text); does return data but only inside the Timer function.

  Future _destinationOnSearchChanged() async {
        dynamic results;
    
        //Cancels timer if its still running
        if (_apiCityThrottle?.isActive ?? false) {
          _apiCityThrottle.cancel();
        }
        //Makes API call half a second after last typed button
          _apiCityThrottle = Timer(const Duration(milliseconds: 500), () async{
            results =  await getCity(context, _typeAheadController.text);
          });
    
    
        print(results);
        return await results;
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As pskink noted in a comment, you probably should look into existing debounce mechanisms instead of creating your own.

If you still want to proceed down this path: your problem is that create a Timer and then return results immediately. You don't wait for the Timer to fire (and you can't directly await a Timer). In this case, you could use a Completer:

Future _destinationOnSearchChanged() async {
  var timerCompleter = Completer<dynamic>(); 

  // Cancels timer if it's still running.
  _apiCityThrottle?.cancel();

  // Makes API call half a second after last typed button.
  _apiCityThrottle = Timer(const Duration(milliseconds: 500), () async {
    timerCompleter.complete(await getCity(context, _typeAheadController.text));
  });

  var results = await timerCompleter.complete();
  print(results);
  return results;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...