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?
StatelessWidgetwithcontextas 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();
}
}
StatefulWidget, which doesn't really host any state, but has niceronPressedmethod 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:
