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

Categories

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

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

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