Member-only story
Flutter — Difference between functions and classes to create reusable widgets?
To make up for some misunderstanding: This is not about functions causing problems, but classes solving some.
3 min readSep 12, 2021
Flutter wouldn’t have StatelessWidget if a function could do the same thing. Similarly, it is mainly directed at public widgets, made to be reused. It doesn’t matter as much for private functions made to be used only once — although being aware of this behavior is still good.
There is an important difference between using functions instead of classes, that is: The framework is unaware of functions, but can see classes.
Consider the following “widget” function:
Widget functionWidget({ Widget child}) {
return Container(child: child);
}
used this way:
functionWidget(
child: functionWidget(),
);
And it’s class equivalent:
class ClassWidget extends StatelessWidget {
final Widget child; const ClassWidget({Key key, this.child}) : super(key: key); @override
Widget build(BuildContext context) {
return Container(
child: child,
);
}
}