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
3.0k views
in Technique[技术] by (71.8m points)

multithreading - Build a progress view for a long running function

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!


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

1 Reply

0 votes
by (71.8m points)

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
        );
      },
    );

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

...