Flutter requires inline event handlers because BuildContext is inline?

Question

Asked by Kernel J on November 05, 2021 (source).

Is it true that Flutter encourages inline event handlers because it is the only way to obtain the BuildContext? e.g.,

class X extends StatelessWidget {

handler() {
  //cannot use this if I need the BuildContext
}

Widget build(BuildContext ctx) {
  return Scaffold(
    home: TextButton(
      text: Text("Click me"),

      onPressed: () { //must be inline, cannot reference "handler" because need "ctx"
        Scaffold.of( ctx ).showSnackBar(/*...*/);
      }
    )
  )
}

}

Most languages encourage simplifying the code by moving event handling code away from the UI but with Flutter, if BuildContext object is needed, there is no "pretty" way to do it except to put the handler inline.

Have I mistaken?

Answer

Question answered by flakerimi (source).

It should be something like that. Pass ctx to functions to have access.

class X extends StatelessWidget {

handler(BuildContext ctx) {
   Scaffold.of( ctx ).showSnackBar(/*...*/);
}

Widget build(BuildContext ctx) {
  return Scaffold(
    home: TextButton(
      text: Text("Click me"),

      onPressed: () => handler(ctx) 
       
      
    )
  )
}

}

Edit, just like @msbit explained

FLUTTER
SHARE: