tags: flutter , programming basics links: Flutter MOC


If you have to call something after build method is complete use addPostFrameCallback

Example scenarios:

  • How to show a Dialog only the first time a page is displayed?
  • How to get dimensions of widget that depends on the device dimensions and other constraints
  • How can I do something once the build is complete?

All these have something in common, we have to wait for the completion of build before doing something.

Usage:

initState

@override
void initState(){
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_){
    showDialog(
      context: context, 
      ...
    );
  });
}

Build method

@override
Widget build(BuildContext context){
  WidgetsBinding.instance.addPostFrameCallback((_) => onAfterBuild(context));
 
  return Container(
    ...
  );
}
 
void _onAfterBuild(BuildContext context){
  // I can now safely get the dimensions based on the context
}

didUpdateWidget

@override
  void didUpdateWidget(TimeRangePageView oldWidget) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (oldWidget.something != widget.something) { 
        // If a prop is changed and you have to call something based on the change
		// jumpToPage(2);
      }
    });
    super.didUpdateWidget(oldWidget);
  }

Common error messages

setState() or markNeedsBuild() called during build.


source: AddPostFrameCallBack