Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...