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

flutter - Flutteronic method of scheduling code to run on the next event loop

This is common in other languages. setTimeout(fn, 0) in JavaScript, and DispatchQueue.main.async() {} in Swift.

How best to do this in Flutter?

I have used Future.delayed(Duration.zero).then(fn), but I don't like it because like JS's setTimeout and unlike swifts DispatchQueue.main.async() {} it doesn't really express the intent, only the behaviour. Is there a way of doing this that is the correct way to do this in Flutter.

question from:https://stackoverflow.com/questions/65831125/flutteronic-method-of-scheduling-code-to-run-on-the-next-event-loop

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

1 Reply

0 votes
by (71.8m points)

Use addPostFrameCallback

WidgetsBinding.instance
          .addPostFrameCallback((timestamp) {
        print("I'm running after the frame was built");
    });

This will cause your callback function to run right after flutter has finished building the current frame.

Note that the callback will only run once, if you want to reschedule it for each build, set the callback at the beginning of the build function.

@override
Widget build(BuildContext context) {
    WidgetsBinding.instance
          .addPostFrameCallback((timestamp) {
        print("I'm running after the frame was built");
    });

    return Container();
}

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

...