Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a button which calls a long running function which runs some kind of loop:

void runLongRunningFunction() {
  for (int i = 0; i < 100000; i++) {
    doSth();
  }
}

...

onPressed: () {
  runLongRunningFunction();
}

Now I want to reach two goals:

  1. The function should not block the UI: Currently the UI freezes as long as the function runs.
  2. Instead it should show some kind of progress, maybe a Text() widget which updates a percentage or even better, a progress bar.

So:

  1. How can I decouple the function from the UI?
  2. How can I return some intermediate values from the function calculation (e.g. the current value of the iterator i) to the UI to update my progress view while the function is still running?

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

You should use FutureBuilder widget.

   Future<String> _runLongRunningFunction() async {
      String result;
      for (int i = 0; i < 100000; i++) {
        ...
      }
      return result;
    }
        
    FutureBuilder<String>(
      future: runLongRunningFunction(),
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        Widget child;
        if (snapshot.hasData) {
          child = Text(snapshot.data);
        } else if (snapshot.hasError) {
          child = Text('${snapshot.error}');
        } else {
          child = CircularProgressIndicator();
        }
        return Center(
            child: child
        );
      },
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...