Search code examples
flutterdart

Is it okay declare functions inside the build method?


I have been declaring functions inside the build method and now I am wondering whether this is a bad practice.

@override
Widget build(BuildContext context) {

  void doRegister() async {
    ...
  }

  return Scaffold(
    ...
  );
}

Are there any problems with this approach and should I declare functions outside of the build method?


Solution

  • The other answers seem to confuse declaring and calling.

    It is fine to declare functions inside build, but you shouldn't call a function on every build unless required (for example to update a value every frame).

    See this answer for a comparison: https://stackoverflow.com/a/64205905/11212916