Home > Blockchain >  Coding convention on passing BuildContext in Stateless widgets
Coding convention on passing BuildContext in Stateless widgets

Time:06-03

This is a small nit that has been bugging me when writing flutter code.

When writing a StatelessWidget, one has to pass around the context to methods manually, as opposed to StatefulWidget where it is available as an instance variable on the State class.

My doubt is - should I convert all my StatelessWidgets to StatefulWidgets so I don't have to pass around context to all my onPressed methods?


E.g. Which is the pereferred way to write flutter code?

  1. StatelessWidget with context as function argument
class PopButton extends StatelessWidget {
  const PopButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialButton(onPressed: () => onPressed(context));
  }

  void onPressed(BuildContext context) {
    Navigator.of(context).pop();
  }
}
  1. StatefulWidget, which doesn't really host any state, but has nicer onPressed method calls
class PopButton extends StatefulWidget {
  const PopButton({Key? key}) : super(key: key);

  @override
  State<PopButton> createState() => _PopButtonState();
}

class _PopButtonState extends State<PopButton> {
  @override
  Widget build(BuildContext context) {
    return MaterialButton(onPressed: onPressed);
  }

  void onPressed() {
    Navigator.of(context).pop();
  }
}

CodePudding user response:

It's totally ok to pass a BuildContext in methods of your widgets. The only thing you shouldn't do is to create methods that has a "Widget" return type, because it affects performance. Also you need to consider prioritising the use of Sateless over Stateful, because:

  • Stateless widgets don't have a separate State object that Flutter should store (better performance)
  • Stateful widgets will produce issues related to attaching correct State instance when using them inside modifiable ListViews and similar widgets (in case you don't use Keys)

So answering your question the 1'st option is more accurate in my opinion.

CodePudding user response:

StatelessWidgets are immutable and could be optimized by the const keyword, also StatefulWidget is a subclass of StatelessWidget, so it is better to use StatelessWidget wherever is possible.

these answers probably will help you to decide which widget type is suitable for you:

  1. https://stackoverflow.com/a/59310208/9455518

  2. https://fluttercentral.com/Articles/Post/14/Stateless_and_Stateful_Widgets_and_their_performance_considerations

  3. https://medium.com/flutter-community/flutter-stateful-vs-stateless-db325309deae

  • Related