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 StatelessWidget
s to StatefulWidget
s 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?
StatelessWidget
withcontext
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();
}
}
StatefulWidget
, which doesn't really host any state, but has niceronPressed
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();
}
}