1

This discussion in github

https://github.com/flutter/flutter/issues/19269

discusses the reasons you should use a Stateless class definition over a function component to define your Widget compositions.

Widget functionWidgetComposition() => Text('hello');

class MyWidgetComposition extends StatelessWidget {
  Widget build(BuildContext context) => Text('hello');
}

If I understood correctly, the reasons to use Stateless are the following...

  1. Do I need access to context?
  2. Do I care that it won't be rebuilt via hot reload? (or will I remember)
  3. Do I need to associate my Widget with a key?
  4. Will this Widget ever be a constant?
  5. Does this widget ever need to be rebuilt?

It feels quite compelling to always use Stateless as a fairly standard rule but the functional style is so much more concise, especially when you have a few parameters. I feel functional components will improve readability in my code. Should I always use Stateless classes then or is it ok to use what React call functional components in some situations?

atreeon
  • 21,799
  • 13
  • 85
  • 104
  • 2
    I do not think that this is a good question for *StackOverflow* because it is **primarily opinion based**. I read through the thread on GitHub and found out that the question was very nicely answered there already by Flutter team members. – creativecreatorormaybenot Aug 04 '18 at 20:55
  • Took the liberty to add a few more points toward classes on the github discussion – Rémi Rousselet Aug 04 '18 at 21:07

1 Answers1

2

From https://github.com/flutter/flutter/issues/19269#issuecomment-404667287

Ya, the main difference is in how it links to the Element tree (in that functions don't get references to Elements themselves and won't get triggered to rebuild themselves via the Element tree).

Some other examples:

  • If your subtree depends on an InheritedWidget, a StatelessWidget will get surgically be marked to rebuild itself. If you used a function, the widget that gave the function its BuildContext will get rebuilt.
    • A function itself won't get called to rebuild during hot reload. Someone else will have to bring it along. If you just passed a function into runApp at the root of your application, nothing will be rebuilt during hot reload.

For the full discussion see https://github.com/flutter/flutter/issues/19269

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567